Greedy Algorithm-maximum sum of at least K consecutive intervals

Source: Internet
Author: User

For an integer N, it indicates the number of integers in the interval. Finding at least K consecutive numbers is the largest sum of the segments in the interval.

The range of N is 1 ~ 10 ^ 6. K (-1000 ~ 1000 );

Analysis: This question looks a bit like a tree array, but if you want to find the sum of at least K consecutive numbers in the interval is the largest, it may be a bit difficult. At most, it is the sum of a certain range.

However, we can follow this idea: sum (N)-sum (I )?.

If we think like this, we need to judge n-I> = K; then another way: Find the minimum value before I and find the maximum value after I + K. In this way, sum (N)-sum (I) must be the largest in the I-th loop.

For every such loop, I only need to define a variable to receive a maximum value (sum (N)-sum (I) and compare it with the next one.

Clear thinking,CodeIt should be easy to write.

 # include 
  
    # include 
   
     using namespace STD; int N, K; int A [1000005]; int INF = 0x7fffffff; void maxsum () {int L = inf; // The maximum value, can pass the value to L (less than its value ). Int r = inf + 1; // The minimum value. It can pass the value to R (greater than its value ). For (INT I = K; I <= N; I ++) {L = L 
     A [I]-l? R: A [I]-l; // check the maximum value after I.} Cout 
     
       A [I]; A [I] + = A [I-1];} maxsum ();} return 0;} 
     
   
  

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.