Maximum Investment Return UVALive7658

题意:给出 n 天中每天的股票价格,Joe 需要决定在哪天买哪天卖,他的这些决定构成了这样一些数对 (b1,s1),(b2,s2),,(bm,sm) ,其中 di 为买入的时间, si 为卖出的时间,并且 m<k and 1b1<s1<b2<s2<<bm<smn

思路:想要赚到尽量多的钱我们肯定要在价格尽量低的时候买入,在价格尽量高的时候卖出。由于 b1s1 是按从小到大来的,所以我们让每一个 (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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值