Maximum Size Subarray Sum - rFronteddu/general_wiki GitHub Wiki

The Maximum Size Subarray Sum Equals k problem asks you to find the length of the longest contiguous subarray that sums to a given integer k.

Problem: You're given an array of integers nums and an integer k. Your goal is to return the maximum length of a contiguous subarray whose sum equals k. If no such subarray exists, return 0.


import java.util.HashMap;

public class Solution {
    

    public int maxSubArrayLen(int[] nums, int k) {
        Map<Integer, Integer> sumMap= new HashMap<>();
        int sum= 0;
        int maxLen = 0;
      
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            // i is the current longest index
            if (sum == k) {
                maxLen = i + 1;
            }

            // If (sum - k) exists in the map, it means there's a subarray that sums to k
            if (sumMap.containsKey(sum - k)) {
                maxLen = Math.max (maxLength, i - sumMap.get (sum - k));
            }  

            // Only store the first occurrence of a cumulative sum to get the longest subarray
            if (!sumMap.containsKey (sum)) {
                sumMap.put(sum, i);
            }
        }        
        return maxLen;
    }