Saturday, January 9, 2016

Leetcode: Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
Example 1:
Given nums = [1, -1, 5, -2, 3]k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
Understand the problem:
The problem is equal to: find out a range from i to j, in which the sum (nums[i], ..., nums[j]) = k. What is the maximal range? 

So we can first calculate the prefix sum of each number, so sum(i, j) = sum(j) - sum(i - 1) = k. Therefore, for each sum(j), we only need to check if there was a sum(i - 1) which equals to sum(j) - k. We can use a hash map to store the previous calculated sum. 

Code (Java):
public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int maxLen = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1); // IMPOARTANT
        int sum = 0;
        
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (!map.containsKey(sum)) {
                map.put(sum, i);
            }
            
            if (map.containsKey(sum - k)) {
                maxLen = Math.max(maxLen, i - map.get(sum - k));
            }
        }
        
        return maxLen;
    }
}

Comments:
Note the map.put(0, -1). We need to put this entry into the map before, because if the maximal range starts from 0, we need to calculate sum(j) - sum(i - 1). 

8 comments:

  1. Hi,
    if array = {1, 2, 1, 0, 1, 2, 1}
    and k = 3
    it should return 5 (longest sub-array is from 1 included to 5 included)
    but it returns 3

    ReplyDelete
    Replies
    1. indexes 3 to 5, using a zero-base (i3=0, i4=1, i5=2 -> 0+1+2 -> 3)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Dictionary map = new Dictionary();
    int sum = 0, maxLength = 0;
    for (int i = 0; i < nums.Length; i++)
    {
    sum += nums[i];
    if (sum == k)
    {
    maxLength = i + 1;
    }
    if (!map.ContainsKey(sum))
    {
    map.Add(sum, i);
    }
    if (map.ContainsKey(sum - k))
    {
    maxLength = Math.Max(maxLength, i - map[sum - k]);
    }
    }

    return maxLength;

    ReplyDelete
  5. What a genius!!! Thank you for your clear explanation! I am from the future 2021, and thank you a random stranger from 2016!!

    ReplyDelete