Money----思维+模拟

链接:https://ac.nowcoder.com/acm/contest/295/B

题目描述

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

题目大意:

有n个商店,编号从1到n。编号为 i 的商店有一个价格 a[ i ]。

小白兔想按从1到n的顺序参观这些商店。

每到一个商店,小白兔可以在这里花费a[ i ]美元购买一种产品,或者出售一种产品以获得a[i]美元。

白兔身上只能携带一种产品。

要求的是白兔参观完所有商店后的最大利润是多少。并且希望在获取最大利润的同时,交易的数量是最少的。

ps:白兔一开始有无限的钱。

解题思路:

我们的思路 就是

当我们手里没商品的时候  我们需要选择一个买入商品的地方 如何选呢?

先买下第一个商品 花费记为o  紧接着的第二个商品 如果说价格低于o  那么其实我们不应该买第一个的  应该从第二个开始买

所以这个时候我们做更新操作  o的值更新为第二个 以此类推 如果接下来的还比o小 我们继续更新(此操作是在纠正买东西的位置)

当我们手里有商品的时候  我们需要选择一个卖出商品的地方 如何选呢?

当我们第一次遇到大于o的值的时候  我们就卖掉商品 那么获利就是a[ i ] - o   交易次数累加2  然后我们把o更新为a[ i ]

接着走如果遇到的还大于o  那么说明我们刚才卖的早了  应该在这里卖  所以我们将获利 再累加上a[ i ] - o 但是不改变交易次数(这个操作是在纠正卖商品的地点    如何控制什么时候改变交易次数呢   就是看手中有商品没  手中有的时候  卖掉时 交易次数+2  然后就把flag置为0 代表手中没商品  接下来遇到a[ i ]再比o大 就只更新o 不改变次数 )

以上两种情况交替使用 遍历一遍就得到了最大利润 和 最小交易次数(什么叫交替使用?  身上没商品的时候  选择买商品的位置  选好了  就要选择卖商品的位置  卖完了 就要选择买商品的位置)

最后再注意一点  当a[ i ]==o的时候 我们不进行任何操作 跳过即可 因为不会获利(注意  也不要改变flag的状态)

代码

#include<iostream>
#include<string.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+7;
ll a[maxn];
int T,n;
int main(){
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        //o代表当前手里买的商品的价格
        //cnt代表交易次数
        //flag为1代表当前手里买了商品 为0代表手里没商品
        ll o,cnt=0,sum=0,flag=1;
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
            if(i==1){
                o=a[1];flag=1;
            }
            else{
                if(a[i]<o){
                    o=a[i];flag=1;
                }
                else if(a[i]>o){
                    if(flag==1){
                        sum+=a[i]-o;o=a[i];
                        cnt+=2;flag=0;
                    }
                    else{
                        sum+=a[i]-o;o=a[i];
                    }
                }
            }
        }
        printf("%lld %lld\n",sum,cnt);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/holly_Z_P_F/article/details/84670836