Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 19, 2016 03:28
Show Gist options
  • Save cangoal/d5e14fd15064c8776cd241e57c3e0f5a to your computer and use it in GitHub Desktop.
Save cangoal/d5e14fd15064c8776cd241e57c3e0f5a to your computer and use it in GitHub Desktop.
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?
public int maxSubArrayLen(int[] nums, int k) {
if(nums == null || nums.length == 0) return 0;
int[] sums = new int[nums.length + 1];
Map<Integer, Integer> map = new HashMap<>();
// map.put(0, -1);
for(int i = 0; i < nums.length; i++){
sums[i+1] = sums[i] + nums[i];
map.put(sums[i+1], i+1);
}
int max = Integer.MIN_VALUE;
for(int i = 0; i < sums.length; i++){
int val = k + sums[i];
if(map.containsKey(val)){
max = Math.max(max, map.get(val) - i);
}
}
return max > 0 ? max : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment