largest subarray with sum k code example

Example 1: minimum subarray size with sum >k

def smallestSubWithSum(arr, n, x):
 
    # Initialize current sum and minimum length
    curr_sum = 0
    min_len = n + 1
 
    # Initialize starting and ending indexes
    start = 0
    end = 0
    while (end < n):
 
        # Keep adding array elements while current
        # sum is smaller than or equal to x
        while (curr_sum <= x and end < n):
            curr_sum += arr[end]
            end += 1
 
        # If current sum becomes greater than x.
        while (curr_sum > x and start < n):
 
            # Update minimum length if needed
            if (end - start < min_len):
                min_len = end - start
 
            # remove starting elements
            curr_sum -= arr[start]
            start += 1
 
    return min_len

Example 2: find longest subarray by sum

def max_length(s, k):
    current = []
    max_len = -1 # returns -1 if there is no subsequence that adds up to k.
    for i in s:
        current.append(i)
        while sum(current) > k: # Shrink the array from the left, until the sum is <= k.
           current = current[1:]
        if sum(current) == k:
            max_len = max(max_len, len(current))

    return max_len

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;
    }
}

Tags:

Java Example