Bit1011 maximum sum II

Source: Internet
Author: User

Question

Returns a sequence of consecutive subsequences with a length not greater than K.

The sum of the subsequences is as large as possible.

For sequence a [0], a [1], a [n-1]

Calculate sum [0], sum [1], sum [n-1]

Sum [I] = A [0] + A [1] +... A [I]

For the largest word sequence and a [I], a [I + 1], a [J]

For sum [J]-sum [I-1]

For J, you need to locate the I-1 so that sum [J]-sum [I-1] is the largest

And J-I <K

This process can be implemented using monotonous queues.

#include<iostream>#include<algorithm>#include<cstdio>#include<deque>using namespace std;int a[50010];int sum[50010];class T{public:int num;int index;};int main(){//freopen("in.txt","r",stdin);int total;scanf("%d",&total);while(total--){int ans=INT_MIN;int n,k;scanf("%d %d",&n,&k); for(int i=0;i<n;i++){scanf("%d",&a[i]);if(a[i]>ans){ans=a[i];}}sum[0]=a[0];for(int i=1;i<n;i++){sum[i]=sum[i-1]+a[i];}deque<T>Q;T tt;tt.index=-1;tt.num=0;Q.push_back(tt);for(int i=0;i<n;i++){while(!Q.empty()&&i-Q.front().index>=k+1){Q.pop_front();}if(!Q.empty()&&ans<sum[i]-Q.front().num){ans=sum[i]-Q.front().num;}while(!Q.empty()&&Q.back().num>=sum[i]){Q.pop_back();}T temp; temp.index=i;temp.num=sum[i];Q.push_back(temp);}printf("%d\n",ans);}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.