[LeetCode] 209. Minimum Size Subarray Sum
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.
For example, given the array
the subarray
[2,3,1,2,4,3]
and s = 7
,the subarray
[4,3]
has the minimal length under the problem constraint.
More practice:
Follow up:
There is an O(nlogn) solution using binary search. First, calculate the prefix sums of the array. Second, iterate through the array, use binary search to find the first element in prefix sums that is larger than equal to prefix sum of the current element + s.
Solution 2:
Time complexity: O(nlogn).
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Thought process:
Sliding window.
Iterate through the array. Add numbers until current sum >= s. Record current sub-array length. As a new number is added, check if I can remove a number from the beginning of the sub-array without reducing current sum below s. Keep track of new sub-array length and minimum length.
Iterate through the array. Add numbers until current sum >= s. Record current sub-array length. As a new number is added, check if I can remove a number from the beginning of the sub-array without reducing current sum below s. Keep track of new sub-array length and minimum length.
Solution 1:
Time complexity: O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public int minSubArrayLen(int s, int[] nums) { int i = 0; int min = 0; int sum = 0; for (int j = 0; j < nums.length; j++) { sum += nums[j]; while (sum >= s) { min = min == 0 ? j - i + 1 : Math.min(min, j - i + 1); sum -= nums[i]; i++; } } return min; } } |
Time complexity: O(n).
Follow up:
There is an O(nlogn) solution using binary search. First, calculate the prefix sums of the array. Second, iterate through the array, use binary search to find the first element in prefix sums that is larger than equal to prefix sum of the current element + s.
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Solution { public int minSubArrayLen(int s, int[] nums) { int[] prefixSum = new int[nums.length + 1]; for (int i = 0; i < nums.length; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } int length = 0; for (int i = 0; i < prefixSum.length - 1; i++) { int right = Arrays.binarySearch(prefixSum, i, prefixSum.length, prefixSum[i] + s); if (right < 0) { right = - (right + 1); } if (right == prefixSum.length) { continue; } length = length == 0 ? right - i : Math.min(length, right - i); } return length; } } |
Time complexity: O(nlogn).
Comments
Post a Comment