Skip to content

fix the issue #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 33 additions & 17 deletions src/main/java/com/fishercoder/solutions/_325.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,38 @@ public class _325 {

public static class Solution1 {
public int maxSubArrayLen(int[] nums, int k) {
Map map = new HashMap();
int sum = 0;
int max = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum == k) {
max = i + 1;
} else if (map.containsKey(sum - k)) {
max = Math.max(max, i - map.get(sum - k));
}
if (!map.containsKey(sum)) {
map.put(sum, i);
}
}
return max;
}
int n = nums.length;
// HashMap to store (sum, index) tuples
HashMap map = new HashMap<>();
int sum = 0, maxLen = 0;

// traverse the given array
for (int i = 0; i < n; i++) {

// accumulate sum
sum += arr[i];

// when subarray starts from index '0'
if (sum == k)
maxLen = i + 1;

// make an entry for 'sum' if it is
// not present in 'map'
if (!map.containsKey(sum)) {
map.put(sum, i);
}

// check if 'sum-k' is present in 'map'
// or not
if (map.containsKey(sum - k)) {

// update maxLength
if (maxLen < (i - map.get(sum - k)))
maxLen = i - map.get(sum - k);
}
}

return maxLen;
}

}
}