A series integer a0,a1......an-1 and integer s with a given length of N. The minimum value of the length of a continuous sub-sequence with a sum not less than S is calculated. If the solution does not exist, the output is 0.
Input n=10
S=15
a=[5,1,3,5,10,7,4,9,2,8]
Output
2 [5,10]
functionsolve () {varRes=n+1; varS=0,t=0,sum=0; for(;;) { while(t<n&&sum<S) {Sum+=a[t++]; } if(Sum<s) { Break} res=math.min (res,t-s); Sum-=a[s++]; } if(res>N) { //solution does not existRes=0; } returnRes;}
Do the following code parsing, S is the array of the Left Sentinel, T is the right Sentinel function solve () { var res=n+1; var s=0,t=0,sum=0; for (;;) {//As long as this condition is met, the right Sentinel keeps t++ to the right while (t<n&&sum<s) { sum+=a[t++]; } Right Sentinel runs to n+1, or disconnects if (sum<s) {break}//update length res=math.min (res,t-s);//Left Sentry right s++ sum-=a[s++]; } if (res>n) { //solution does not exist res=0; } return res;}
The algorithm of the ruler method JavaScript