Skip to content

Commit 8466382

Browse files
maximum size subarray sum equals k
1 parent 7a27663 commit 8466382

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
import utils.CommonUtils;
7+
8+
public class MaximumSizeSubarraySumEqualsK {
9+
public int maxSubArrayLen_On_solution(int[] nums, int k) {
10+
Map<Integer, Integer> map = new HashMap();
11+
int sum = 0, max = 0;
12+
for(int i = 0; i < nums.length; i++){
13+
sum += nums[i];
14+
if(sum == k) max = i+1;
15+
else if(map.containsKey(sum-k)) max = Math.max(max, i-map.get(sum-k));
16+
if(!map.containsKey(sum)) map.put(sum, i);
17+
}
18+
return max;
19+
}
20+
21+
22+
public static int maxSubArrayLen_On2_solution(int[] nums, int k) {
23+
//NOTES: didn't finish this one
24+
int[] sums = new int[nums.length];
25+
int max = 0;
26+
for(int i = 0; i < nums.length; i++){
27+
if(i == 0) sums[i] = nums[i];
28+
else sums[i] = sums[i-1] + nums[i];
29+
if(sums[i] == k) max = i+1;//then this one must be the max
30+
}
31+
CommonUtils.printArray(sums);
32+
//do computation for each possible subarray of sums and find the max length
33+
return max;
34+
}
35+
36+
public static void main(String...args){
37+
//correct answer is 4
38+
// int[] nums = new int[]{1, -1, 5, -2, 3};
39+
// int k = 3;
40+
41+
//correct answer is 2
42+
int[] nums = new int[]{-2, -1, 2, 1};
43+
int k = 1;
44+
maxSubArrayLen_On2_solution(nums, k);
45+
}
46+
47+
}

0 commit comments

Comments
 (0)