From ba3e9cb3b079e5f8ccc207e72d8759983ef03b8e Mon Sep 17 00:00:00 2001 From: Nishant Nirmal Date: Wed, 1 Apr 2020 15:44:06 +0530 Subject: [PATCH] Minimum Size Subarray Sum --- 0209-Minimum-Size-Subarray-Sum.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 0209-Minimum-Size-Subarray-Sum.py diff --git a/0209-Minimum-Size-Subarray-Sum.py b/0209-Minimum-Size-Subarray-Sum.py new file mode 100644 index 0000000..ff7fc3a --- /dev/null +++ b/0209-Minimum-Size-Subarray-Sum.py @@ -0,0 +1,24 @@ +''' +Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. + +Example: + +Input: s = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: the subarray [4,3] has the minimal length under the problem constraint. + +Follow up: +If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). +''' +# Time Complexity: O(n) +# Space Complexity: O(1) +class Solution: + def minSubArrayLen(self, s: int, nums: List[int]) -> int: + i, res = 0, len(nums) + 1 + for j in range(len(nums)): + s -= nums[j] + while s <= 0: + res = min(res, j - i + 1) + s += nums[i] + i += 1 + return res % (len(nums) + 1)