The algorithm of the ruler method JavaScript

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.