1
+ # Given an array of positive integers nums and a positive integer target, return the
2
+ # minimal length of a
3
+ # subarray
4
+ # whose sum is greater than or equal to target. If there is no such subarray, return
5
+ # 0 instead.
6
+
7
+
8
+
9
+ # Example 1:
10
+
11
+ # Input: target = 7, nums = [2,3,1,2,4,3]
12
+ # Output: 2
13
+ # Explanation: The subarray [4,3] has the minimal length under the problem constraint.
14
+ # Example 2:
15
+
16
+ # Input: target = 4, nums = [1,4,4]
17
+ # Output: 1
18
+ # Example 3:
19
+
20
+ # Input: target = 11, nums = [1,1,1,1,1,1,1,1]
21
+ # Output: 0
22
+
23
+
24
+ # Constraints:
25
+
26
+ # 1 <= target <= 109
27
+ # 1 <= nums.length <= 105
28
+ # 1 <= nums[i] <= 104
29
+
30
+
31
+ # Follow up: If you have figured out the O(n) solution, try coding another solution of
32
+ # which the time complexity is O(n log(n)).
33
+
34
+
35
+ from typing import List
36
+ class Solution :
37
+ def minSubArrayLen (self , target : int , nums : List [int ]) -> int :
38
+ prefix_sum = left = 0
39
+ ln = len (nums )
40
+ ans = ln + 1
41
+
42
+ for i in range (ln ):
43
+ prefix_sum += nums [i ]
44
+ while prefix_sum >= target :
45
+ ans = min (ans , i - left + 1 )
46
+ prefix_sum -= nums [left ]
47
+ left += 1
48
+ if ans > ln :
49
+ return 0
50
+ else :
51
+ return ans
0 commit comments