Skip to content

325. Maximum Size Subarray Sum Equals k 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int maxSubArrayLen(vector<int>& nums, int k) {
    int ans = 0;
    int prefix = 0;
    unordered_map<int, int> prefixToIndex{{0, -1}};

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      const int target = prefix - k;
      if (prefixToIndex.count(target))
        ans = max(ans, i - prefixToIndex[target]);
      if (!prefixToIndex.count(prefix))
        prefixToIndex[prefix] = i;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int maxSubArrayLen(int[] nums, int k) {
    int ans = 0;
    int prefix = 0;
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      final int target = prefix - k;
      if (prefixToIndex.containsKey(target))
        ans = Math.max(ans, i - prefixToIndex.get(target));
      prefixToIndex.putIfAbsent(prefix, i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def maxSubArrayLen(self, nums: List[int], k: int) -> int:
    ans = 0
    prefix = 0
    prefixToIndex = {0: -1}

    for i, num in enumerate(nums):
      prefix += num
      target = prefix - k
      if target in prefixToIndex:
        ans = max(ans, i - prefixToIndex[target])
      if prefix not in prefixToIndex:
        prefixToIndex[prefix] = i

    return ans
Back to top