Tuesday, December 27, 2016

Leetcode/ F家,Palantir - 325.Maximum Size Subarray Sum Equals (HashMap)

325.Maximum Size Subarray Sum Equals k (HashMap)
https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/

  • Difficulty: Medium
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.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
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?

思路: Use HashMap to store the sum at each index, <sum, index> We guaranteed the max size to add from begin of array, so we do not update map if key is found.
         In every loop, check if (sum-k) exist, track the max len: i - map.get(sum - k) no need to + 1 to len, because subarray starts after previous sum - map.get(sum - k)
         !Watch case where subarray start from begin (sum == k), but we can do minus still by pre-adding <0,-1> to map

Complexity: O(N)time O(N)space

public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        int len = 0;
        int sum = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();//<sum, index>
        map.put(0, -1);//or we can in loop use if(sum == k),len = i+1; since longest will be from begin of array 
        for(int i = 0; i < nums.length; i++){
            sum += nums[i];
            if(!map.containsKey(sum))
                map.put(sum, i);
            if(map.containsKey(sum - k)){
                len = Math.max(len , i - map.get(sum - k));
            }
        }
        return len;
    }
}

No comments:

Post a Comment