MediumNo. 0325LeetCode Premium
Maximum Size Subarray Sum Equals k — LeetCode 325 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Hash Table, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- 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.
Python solution
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the length of the array nums
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 325. Maximum Size Subarray Sum Equals k is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0523 | Continuous Subarray Sum | Medium |
| 0525 | Contiguous Array | Medium |
| 0560 | Subarray Sum Equals K | Medium |
| 0930 | Binary Subarrays With Sum | Medium |
| 0974 | Subarray Sums Divisible by K | Medium |
| 1074 | Number of Submatrices That Sum to Target | Hard |
Frequently asked questions
- How hard is LeetCode 325. Maximum Size Subarray Sum Equals k?
LeetCode 325. Maximum Size Subarray Sum Equals k is rated Medium on LeetCode.
- What is the time complexity of LeetCode 325. Maximum Size Subarray Sum Equals k?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 325. Maximum Size Subarray Sum Equals k?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 325. Maximum Size Subarray Sum Equals k cover?
LeetCode 325. Maximum Size Subarray Sum Equals k is tagged Array, Hash Table and Prefix Sum on LeetCode.
- Is LeetCode 325. Maximum Size Subarray Sum Equals k a premium problem?
Yes. LeetCode 325. Maximum Size Subarray Sum Equals k is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.