牛客网暑期acm多校训练营(第二场) D money

题目描述 
White Cloud has built n stores numbered from 1 to n.
White Rabbit wants to visit these stores in the order from 1 to n.
The store numbered i has a price a[i] representing that White Rabbit can spend a[i] dollars to buy a product or sell a product to get a[i] dollars when it is in the i-th store.
The product is too heavy so that White Rabbit can only take one product at the same time.
White Rabbit wants to know the maximum profit after visiting all stores.
Also, White Rabbit wants to know the minimum number of transactions while geting the maximum profit.
Notice that White Rabbit has infinite money initially.


输入描述:
The first line contains an integer T(0<T<=5), denoting the number of test cases.
In each test case, there is one integer n(0<n<=100000) 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.

输入
1
5
9 10 7 6 8
输出
3 4

题意:从编号1→n遍历商店,每个商店都有一个价格a[i],White Rabbit抵达一个商店时可以选择以价格a[i]买商店里的商品或者以价格a[i]卖掉手中的物品,求White Rabbit遍历完商店之后的最大利润和买卖操作次数。

贪心:只有在第i+1次价格严格大于的情况下才在第i次买进,然后模拟一遍就可以了。

#include <bits/stdc++.h>

using namespace std;
#define ll long long
const int maxn=1e5+10;
const int INF=0x3f3f3f3f;

ll a[maxn];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%lld",&a[i]);
        }
        ll sum=0;
        ll ans=0;
        int flag=0;//手中的状态
        a[n]=0;//不能忘记更新。。
        for(int i=0;i<n;i++)
        {
            if(!flag&&a[i]<a[i+1])
            {
                sum-=a[i];
                ans++;
                flag=1;
            }
            if(flag&&a[i]>a[i+1])
            {
                sum+=a[i];
                ans++;
                flag=0;
            }
        }
        printf("%lld %lld\n",sum,ans);
    }
    return 0;
}
/*
1
5
9 10 7 6 8
*/
 

猜你喜欢

转载自blog.csdn.net/snayf/article/details/81161642