Question:
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.
Solution:
Solution 1: brutal force + pruning — 239ms
class Solution { public: //solution 1 brutal force int minSubArrayLen( int s, vector<int>& nums ) { int n = nums.size(), len = n + 1; for( int i = 0; i < n; ++i ){ int sum = 0, localLen = 0, j; for(j = i; j < nums.size(); ++j ){ sum += nums[j]; localLen++; if ( sum >= s || localLen == len ){ break; } } if (j < nums.size()) len = min(localLen, len); else if ( sum < s ) break; } return ( len > n ) ? 0 : len; } };
Solution 2: O(n) –8ms
class Solution { public: //Solution 2: using sliding window O(n) -- 8ms int minSubArrayLen(int s, vector<int>& nums) { int n = nums.size(); int end = 0, start = 0, sum = 0, len = INT_MAX; while( end < n ){ //find the sliding window while( end < n && sum < s ) sum += nums[end++]; //find it change the the sliding window's start point while( sum >= s && start < n){ len = min( len, end - start ); sum -= nums[start++]; } } return (len > n ) ? 0 : len; } };