2018牛客网暑期ACM多校训练营第二场 D - money(贪心)

题目链接 https://www.nowcoder.com/acm/contest/140#question

【题目描述】
White Cloud is exercising in the playground.
White Cloud can walk 1 meters or run k meters per second.
Since White Cloud is tired,it can’t run for two or more continuous seconds.
White Cloud will move L to R meters. It wants to know how many different ways there are to achieve its goal.
Two ways are different if and only if they move different meters or spend different seconds or in one second, one of them walks and the other runs.

【输入格式】
The first line contains an integer T(T<=5), denoting the number of test cases.
In each test case, there is one integer n(n<=10^5) in the first line,denoting the number of stores.
For the next line, There are n integers in range [0,2147483648), denoting a[1..n].

【输出格式】
For each test case, print a single line containing 2 integers, denoting the maximum profit and the minimum number of transactions.

【题意】
你要按照顺序依次经过n个商店,每到达一个商店你可以购买一件商品,也可以出售你手中的商品。同一时刻你手上最多拿一件商品。在第i个商店购买和出售的代价都是a[i]。
问你经过完n个商店后的最大收益。
同时,在最大化收益的前提下,求最小的交易次数。

【思路】
如果所有相邻商店的代价都不一样,那么最优解一定是在极小值点买入,在极大值点卖出,这样获得的收益是最大的。如果有相邻商店的代价是一样的话,那么可以删掉其它的只留下一个,所以在一开始对数组unique去重一下然后去找极小值和极大值把它们所有差值的和计算出来就可以了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const ll inf=1e17;
const int maxn=100050;

int n;
ll a[maxn];

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        a[0]=inf;
        a[n+1]=-inf;
        for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
        int x=unique(a,a+n+2)-a;
        bool flag=1;//flag==1表示要找极小值买入
        ll ans=0;
        int cnt=0;
        for(int i=1;i<x-1;++i){
            if(flag){
                if(a[i-1]>=a[i] && a[i]<=a[i+1]){
                    ans-=a[i];
                    flag=0;
                    ++cnt;
                }
            }
            else{
                if(a[i-1]<=a[i] && a[i]>=a[i+1]){
                    ans+=a[i];
                    flag=1;
                    ++cnt;
                }
            }
        }
        printf("%lld %d\n",ans,cnt);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值