Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 8, 2017 03:01
Show Gist options
  • Save shailrshah/4224f6be1980d46cb90aef3a99a3a39a to your computer and use it in GitHub Desktop.
Save shailrshah/4224f6be1980d46cb90aef3a99a3a39a to your computer and use it in GitHub Desktop.
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.
/*
To find: A range i..j such that nums[i] + nums[i+1] + ... + nums[j] = sum(i, j) = k
sum(i, j) = sum(0, j) - sum(0, i-1) since for [1 2 3 4], sum(1, 3) = sum(0, 3) - sum(0, 0);
sum(0, j) - sum(0, i-1) = k, or sum(0, i-1) = sum(0, j) - k
For each sum(0, j), check if there was a sum(0, i-1) such that it equals sum(0, j) - k.
*/
public int maxSubArrayLen(int[] nums, int k) {
int sum = 0, max = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1); // incase i = 0
for(int j = 0; j < nums.length; j++) {
sum += nums[j]; // sum is sum(0, j)
if(!map.containsKey(sum)) map.put(sum, j);
if(map.containsKey(sum - k))
max = Math.max(max, j - map.get(sum-k)); // i = map.get(sum-k)
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment