This problem asks to find the maximum length of a subarray whose elements sum up to a given target k
. The optimal solution utilizes the concept of prefix sums and a hash map to achieve a time complexity of O(n).
Approach:
Prefix Sum: We calculate the prefix sum of the array nums
. The prefix sum at index i
represents the sum of all elements from index 0 to i
.
Hash Map: We use a hash map (d
in the code) to store the prefix sums encountered so far along with their corresponding indices. The key is the prefix sum, and the value is its index.
Iteration: We iterate through the array. For each element:
s
.s - k
exists as a key in the hash map. If it does, it means there's a subarray ending at the current index with a sum equal to k
(because s - (s - k) = k
). We update the ans
(maximum length) accordingly.s
and its index i
in the hash map. This is crucial for efficiently finding previous prefix sums.Initialization: We initialize the hash map with {0: -1}
. This handles the case where the subarray starting from index 0 sums up to k
.
Time Complexity: O(n) - We iterate through the array once. Hash map operations (insertion and lookup) take O(1) on average.
Space Complexity: O(n) - In the worst case, the hash map can store all prefix sums.
Code Explanation (Python):
class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
d = {0: -1} # Initialize with {0: -1} to handle subarray starting from index 0
ans = s = 0 # ans stores the maximum length, s stores the current prefix sum
for i, x in enumerate(nums):
s += x # Update prefix sum
if s - k in d: # Check if s - k exists in the hash map
ans = max(ans, i - d[s - k]) # Update max length if a subarray with sum k is found
if s not in d: # Add or update prefix sum in hash map
d[s] = i
return ans
The other languages (Java, C++, Go, TypeScript) follow a very similar logic, adapting the syntax and data structures to their respective languages. The core algorithm remains consistent across all implementations. The use of getOrDefault
in Java and similar mechanisms in other languages elegantly handles cases where s - k
is not found in the map, avoiding KeyError
exceptions.