find Largest sum contiguous Subarray code example
Example 1: find longest subarray by sum
def max_length(s, k):
current = []
max_len = -1
for i in s:
current.append(i)
while sum(current) > k:
current = current[1:]
if sum(current) == k:
max_len = max(max_len, len(current))
return max_len
Example 2: largest subarray of 0's and 1's
public class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int maxlen = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
count = count + (nums[i] == 1 ? 1 : -1);
if (map.containsKey(count)) {
maxlen = Math.max(maxlen, i - map.get(count));
} else {
map.put(count, i);
}
}
return maxlen;
}
}