Problem:
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.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Analysis:
Dynamic programming.
Solutions:
C++:
int minSubArrayLen(int s, vector<int>& nums) {
if(nums.empty())
return 0;
int size = nums.size();
int sum = nums[0];
if(sum >= s)
return 1;
int start = 0;
int end = 1;
int min_length_of_subarray = -1;
while(start <= end) {
if(sum >= s) {
if(start == end - 1)
return 1;
else if(min_length_of_subarray == -1 || min_length_of_subarray > end - start)
min_length_of_subarray = end - start;
sum -= nums[start++];
} else {
if(end == size)
break;
sum += nums[end++];
}
}
return min_length_of_subarray == -1 ? 0 : min_length_of_subarray;
}
Java
:
Python: