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)
public class MaxSizeSubArraySumK {
public static void main(String[] args) {
int arr[] = {2,1,-1,3,5,2,-5,1,-3};
int k = 3;
int max = 0;
int sum = 0;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0;i<arr.length;i++){
sum+=arr[i];
if(sum==k){
max = Math.max(max,i);
}
int diff = sum-k;
if(map.containsKey(diff)){
max= Math.max(max,i-map.get(diff));
}
if(!map.containsKey(sum)){
map.put(sum,i);
}
}
System.out.println(max);
}
result: 8
No comments:
Post a Comment