Skip to content

Commit c134a3e

Browse files
committed
Sync LeetCode submission Runtime - 139 ms (74.12%), Memory - 63.2 MB (40.37%)
1 parent ea6289f commit c134a3e

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a </em><span data-keyword="subarray"><em>subarray</em></span><em> that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3
8+
<strong>Output:</strong> 4
9+
<strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [-2,-1,2,1], k = 1
16+
<strong>Output:</strong> 2
17+
<strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>
25+
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
26+
<li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li>
27+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach: Prefix Sum + Hash Map
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
8+
prefix_sum = longest_subarray = 0
9+
indices = {}
10+
11+
for i, num in enumerate(nums):
12+
prefix_sum += num
13+
14+
if prefix_sum == k:
15+
longest_subarray = i + 1
16+
17+
if prefix_sum - k in indices:
18+
longest_subarray = max(longest_subarray, i - indices[prefix_sum - k])
19+
20+
if prefix_sum not in indices:
21+
indices[prefix_sum] = i
22+
23+
return longest_subarray
24+

0 commit comments

Comments
 (0)