牛客算法周周练1 Maximize The Beautiful Value(前缀和)

链接:https://ac.nowcoder.com/acm/contest/5086/A

题目描述

Today HH finds a non-decreasing sequence(a1,a2…an,ai≤ai+1), he thinks it’s not beautiful so he wants to make it beautiful.
To make it, HH will choose exactly one number and move it forward at least k steps(i.e. you can move ai to aj if k≤i−j), and then he defines the beautiful value F(n) as
HH asks you to calculate max(F(n))

输入描述:

The first line contains an positive integer T(1≤T≤10), represents there are T test cases.
For each test case:
The first line contains two positive integers n,k(1≤n≤105,1≤k<n),the length of the sequence ,the least steps you need to move.
The second line contains n integers a1,a2…an(1≤ai≤108) - the sequence.

输出描述:

For each test case, you should output the max F(n).

示例1

输入
3
5 3
1 1 3 4 5
5 2
1 1 3 4 5
5 1
1 1 3 4 5
输出
46
50
53

思路:

前缀和记录此结点及之前的美丽值,设把aj移动到ai移动后的美丽值==总美丽值 + ai至aj往后移动1格增加的美丽值 - aj往前移损失的美丽值。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e8+8;
ll a[maxn],f[maxn];
ll n,k,sum,ans;
int main()
{
    
    
	int t;
	cin>>t;
	while(t--)
	{
    
    
		cin>>n>>k;
		sum=0;
		for(int i=1;i<=n;i++)
		{
    
    
			cin>>a[i];
			f[i]=a[i]+f[i-1];
			sum+=a[i]*i;
		}
		ans=0;
		for(int i=k+1;i<=n;i++)
		{
    
    
			ans=max(ans,sum+f[i-1]-f[i-1-k]-a[i]*k);
		}
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaolan7777777/article/details/105570765