题意:给出 n 天中每天的股票价格,Joe 需要决定在哪天买哪天卖,他的这些决定构成了这样一些数对 (b1,s1),(b2,s2),⋯,(bm,sm) ,其中 di 为买入的时间, si 为卖出的时间,并且 m<k and 1≤b1<s1<b2<s2<⋯<bm<sm≤n
思路:想要赚到尽量多的钱我们肯定要在价格尽量低的时候买入,在价格尽量高的时候卖出。由于
b1,s1⋯
是按从小到大来的,所以我们让每一个
(bi,si)
对产生的利润最大化,让总共的对数最少。
为此,我们只需要从左往右扫一遍每天的股票价格,每一个
(bi,si)
中的
bi
和
si
分别对应于每一个连续增长(也包括持平)阶段的最初的股票价格和最后的股票价格。
比如:
10天的股票价格分别为1,2,3,4,2,3,3,4,5,1
1,2,3,4是一个阶段,2,3,3,4,5是一个阶段
产生两个队
(1,4)
,
(5,9)
,利润分别为
3×1000
和
4×1000
,根据 m 从大到小取这些利润就好。
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
int n, k;
int p[1010];
vector<int> vec;
bool cmp(int& a, int& b)
{
return a > b;
}
int main()
{
//freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while(T--){
vec.clear();
scanf("%d%d", &n, &k);
int t = 0;
bool first = true;
for(int i=1; i<=n; i++){ //一边读入一边处理
scanf("%d", &p[i]);
if(first){
first = false;
t = p[i];
}
else{
if(p[i]<p[i-1]){
vec.push_back(p[i-1]-t);
t = p[i];
}
else if(p[i]>=p[i-1] && i==n){
vec.push_back(p[i]-t);
}
}
}
sort(vec.begin(), vec.end(), cmp); //从大到小排序
int ans = 0;
int sz = vec.size();
for(int i=0; i< min(k, sz); i++){
ans += 1000*vec[i];
}
printf("%d\n", ans);
}
return 0;
}