Skip to content

Commit 108fc04

Browse files
209. Minimum Size Subarray Sum
Difficulty: Medium 15 / 15 test cases passed. Runtime: 72 ms Memory Usage: 16.2 MB
1 parent 9d7ca1a commit 108fc04

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Medium/209.MinimumSizeSubarraySum.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Given an array of n positive integers and a positive integer s, find the
3+
minimal length of a contiguous subarray of which the sum ≥ s.
4+
If there isn't one, return 0 instead.
5+
6+
Example:
7+
Input: s = 7, nums = [2,3,1,2,4,3]
8+
Output: 2
9+
Explanation: the subarray [4,3] has the minimal length under the problem
10+
constraint.
11+
12+
Follow up:
13+
If you have figured out the O(n) solution, try coding another solution of
14+
which the time complexity is O(n log n).
15+
"""
16+
#Difficulty: Medium
17+
#15 / 15 test cases passed.
18+
#Runtime: 72 ms
19+
#Memory Usage: 16.2 MB
20+
21+
#Runtime: 72 ms, faster than 87.67% of Python3 online submissions for Minimum Size Subarray Sum.
22+
#Memory Usage: 16.2 MB, less than 7.69% of Python3 online submissions for Minimum Size Subarray Sum.
23+
24+
class Solution:
25+
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
26+
if not nums or sum(nums) < s: return 0
27+
if s in nums or s < max(nums): return 1
28+
i = 0
29+
l = length = len(nums)
30+
summ = 0
31+
for j in range(length):
32+
summ += nums[j]
33+
while summ >= s and i <= j:
34+
l = min(l, 1 + j - i)
35+
summ -= nums[i]
36+
i += 1
37+
return l

0 commit comments

Comments
 (0)