例題鏈接:1051-習題-數學考試_2021秋季算法入門班第一章習題:模擬、枚舉、貪心
來源:牛客網
?
時間限制:C/C++/Rust/Pascal 1秒,其他語言2秒
空間限制:C/C++/Rust/Pascal 32 M,其他語言64 M
64bit IO Format: %lld
題目描述
今天qwb要參加一個數學考試,這套試卷一共有n道題,每道題qwb能獲得的分數為ai,qwb并不打算把這些題全做完,
他想選總共2k道題來做,并且期望他能獲得的分數盡可能的大,他準備選2個不連續的長度為k的區間,
即[L,L+1,L+2,....,L+k-1],[R,R+1,R+2,...,R+k-1](R >= L+k)。
輸入描述:
第一行一個整數T(T<=10),代表有T組數據 接下來一行兩個整數n,k,(2<=n<=200,000),(1<=k,2k <= n) 接下來一行n個整數a1,a2,...,an,(-100,000<=ai<=100,000)
輸出描述:
輸出一個整數,qwb能獲得的最大分數
示例1
輸入
復制2 6 3 1 1 1 1 1 1 8 2 -1 0 2 -1 -1 2 3 -1
2 6 3 1 1 1 1 1 1 8 2 -1 0 2 -1 -1 2 3 -1
輸出
復制6 7
6 7
#include<bits/stdc++.h>
using namespace std;
#define int long long
void solve()
{int n, k;cin >> n >> k;vector<int> a(n+1);for (int i = 1; i <= n; i++){cin >> a[i];a[i]+=a[i-1];}int l=-1e18, r=-1e18;for (int i = k; i <= n - k; i++){l = max(l, a[i] - a[i - k]);r = max(r, l+a[i+k]-a[i]);}cout << r << endl;
}
signed main()
{int t;cin>>t;while (t--){solve();}return 0;
}
代碼:其中找這兩個最大值只需要這樣就好,會自動更新。
for (int i = k; i <= n - k; i++){l = max(l, a[i] - a[i - k]);r = max(r, l+a[i+k]-a[i]);}