Largest Sum Contiguous Subarray code example
Example 1: maximum subarray solution leetcode
def approach3(nums):
ans = nums[0]
subarr_sum = nums[0]
for i in range(1, len(nums)):
subarr_sum = max(nums[i], nums[i] + subarr_sum)
ans = max(ans, subarr_sum)
return ans
Example 2: kadane algorithm
public int kadane(int[] arr){
int max_so_far = 0, curr_max = Integer.MIN_VALUE;
for(int i: arr){
max_so_far += i;
if(max_so_far<0) max_so_far = 0;
if(max_so_far>curr_max) curr_max = max_so_far;
}
return curr_max;
}
Example 3: 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;
}
}