|
| 1 | +/* |
| 2 | +https://leetcode.com/problems/minimum-size-subarray-sum |
| 3 | +
|
| 4 | +Given an array of positive integers nums and a positive integer target, |
| 5 | +return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] |
| 6 | +of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input: target = 7, nums = [2,3,1,2,4,3] |
| 10 | +Output: 2 |
| 11 | +Explanation: The subarray [4,3] has the minimal length under the problem constraint. |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: target = 4, nums = [1,4,4] |
| 15 | +Output: 1 |
| 16 | +
|
| 17 | +Example 3: |
| 18 | +Input: target = 11, nums = [1,1,1,1,1,1,1,1] |
| 19 | +Output: 0 |
| 20 | +*/ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} target |
| 24 | + * @param {number[]} nums |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | + var minSubArrayLength = function(target, nums) { |
| 28 | + if(nums.length == 0) { return 0 } |
| 29 | + |
| 30 | + let start = 0; |
| 31 | + let end = 0; |
| 32 | + let currentSum = nums[0]; |
| 33 | + let minWindow = 0; |
| 34 | + let currentWindow = 1; |
| 35 | + |
| 36 | + while(start < nums.length && end < nums.length) { |
| 37 | + currentWindow = (end + 1 - start) |
| 38 | + if(currentSum >= target || (minWindow != 0 && currentWindow > minWindow) ) { |
| 39 | + if(minWindow == 0 || minWindow > currentWindow ) { |
| 40 | + minWindow = currentWindow; |
| 41 | + if(minWindow == 1) { return 1 }; |
| 42 | + } |
| 43 | + currentSum -= nums[start]; |
| 44 | + start++; |
| 45 | + } else { |
| 46 | + end++; |
| 47 | + if(end < nums.length) { |
| 48 | + currentSum += nums[end]; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return minWindow; |
| 54 | +}; |
| 55 | + |
| 56 | +module.exports.minSubArrayLength = minSubArrayLength; |
0 commit comments