codeforces 1373D

題目鏈接

題目大意:

給你一個數組(下標從0開始)

最多旋轉一個子數列

問所有可能中偶數位置上的元素和的最大值

解題思路:

翻轉無非是倒置  即偶變奇  奇變偶  但是區間裏面是數字是不會變化的   數還是那些數  只是位置變了

所以我們只需遍歷數組  更新奇數下標減去偶數下標的最大和   有兩種情況

a[1]-a[0]   a[3]-a[1]  .......

a[1]-a[2]    a[3]-a[4]  ......

最後加上原本的偶數位置的元素和就行

 

代碼如下

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll a[maxn]; 
int main()
{
	int t;
	ll i,ans,sum,maxx,n;
	cin>>t;
	while(t--)
	{
		maxx=0;
		sum=0;
		ans=0;
		cin>>n;
		for(i=0;i<n;i++)
		{
			cin>>a[i];
			if(i%2==0)
			  sum+=a[i];
		}
		for(i=1;i<n;i+=2)
		{
			ans+=a[i]-a[i-1];
			maxx=max(ans,maxx);
			if(ans<0)
			  ans=0;
		}
		ans=0;
		for(i=2;i<n;i+=2)
		{
			ans+=a[i-1]-a[i];
			maxx=max(ans,maxx);
			if(ans<0)
			  ans=0;
		}
		sum+=maxx;
		cout<<sum<<endl;
	} 
	 
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章