LeetCode 0325. Maximum Size Subarray Sum Equals k Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0325. Maximum Size Subarray Sum Equals k

Description

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead.

 

Example 1:

Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example 2:

Input: nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

 

Constraints:

  • 1 <= nums.length <= 2 * 105
  • -104 <= nums[i] <= 104
  • -109 <= k <= 109

Solutions

Solution 1: Hash Table + Prefix Sum

We can use a hash table d to record the first occurrence index of each prefix sum in the array nums, initializing d[0] = -1. Additionally, we define a variable s to keep track of the current prefix sum.

Next, we iterate through the array nums. For the current number nums[i], we update the prefix sum s = s + nums[i]. If s - k exists in the hash table d, let j = d[s - k], then the length of the subarray that ends at nums[i] and satisfies the condition is i - j. We use a variable ans to maintain the length of the longest subarray that satisfies the condition. After that, if s does not exist in the hash table, we record s and its corresponding index i by setting d[s] = i. Otherwise, we do not update d[s]. It is important to note that there may be multiple positions i with the same value of s, so we only record the smallest i to ensure the subarray length is the longest.

After the iteration ends, we return ans.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the array nums.

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def maxSubArrayLen(self, nums: List[int], k: int) -> int: d = {0: -1} ans = s = 0 for i, x in enumerate(nums): s += x if s - k in d: ans = max(ans, i - d[s - k]) if s not in d: d[s] = i return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !