解題思路
先略過不漲的段,找到局部谷價v與其後峰價p;每段都有正利益p−v。用堆疊保存尚未定案的谷峰對。
新谷低於堆頂谷時,舊谷峰已可獨立取利,將其收益存入候選並彈出。新峰不低於舊峰時,兩交易可合併:保留較早的谷,將舊峰到新谷的落差記為多用一次交易能增加的邊際收益。
上述交換保持「每個交易數的最大可得收益」:分開與合併只差中間落差,較低新谷則不必延續舊持股。全部掃完,把剩餘谷峰收益加入候選;最多K次的最優值就是最大K個正邊際收益總和。
時間 O(N+P log P),P為候選數;谷峰堆疊與候選O(N),Python整份輸入O(N)。
Step-by-step animation
谷峰交易合併的邊際利益|價1,5,3,8,谷峰為(1,5),(3,8)。
步驟 1 / 3
兩段上漲
價1,5,3,8,谷峰為(1,5),(3,8)。
1→5
3→8
- 分開收益
- 9
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int &x : a)
cin >> x;
vector<pair<int, int>> st;
vector<int> profit;
int i = 0;
while (i < n) {
while (i + 1 < n && a[i] >= a[i + 1])
i++;
int v = a[i];
while (i + 1 < n && a[i] <= a[i + 1])
i++;
int p = a[i];
i++;
if (p <= v)
continue;
while (st.size() && v < st.back().first) {
profit.push_back(st.back().second - st.back().first);
st.pop_back();
}
while (st.size() && p >= st.back().second) {
profit.push_back(st.back().second - v);
v = st.back().first;
st.pop_back();
}
st.push_back({v, p});
}
for (auto [v, p] : st)
profit.push_back(p - v);
sort(profit.rbegin(), profit.rend());
long long ans = 0;
for (int j = 0; j < min(k, (int)profit.size()); j++)
ans += profit[j];
cout << ans << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。