-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path209 Minimum Size Subarray Sum.py
46 lines (34 loc) · 1.09 KB
/
209 Minimum Size Subarray Sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- coding: utf-8 -*-
"""
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum
≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
Author: Rajeev Ranjan
"""
import sys
class Solution:
def minSubArrayLen(self, s, nums):
"""
Brute force: O(n^2)
two pointers sliding window
minimum length -> sliding window works by shrinking
:type s: int
:type nums: list[int]
:rtype: int
"""
n = len(nums)
S = [0 for _ in xrange(n+1)]
for i in xrange(1, n+1):
S[i] = S[i-1]+nums[i-1]
lo, hi = 0, 1
mini = sys.maxint
while hi <= n:
if S[hi]-S[lo] >= s:
mini = min(mini, hi-lo)
lo += 1
else:
hi += 1
return mini if mini != sys.maxint else 0
if __name__ == "__main__":
assert Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]) == 2