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

链接:https://www.nowcoder.com/acm/contest/140/D
来源:牛客网
 

money

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

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

输入

复制

1
5
9 10 7 6 8

输出

复制

3 4

题意:给出n个商店 每个商店的商品都一样 从1-->n 不能往回走

你可以通低卖高买的方式(商品的售价与收购价均为 Si) 赚取利润(你手上最多只能携带一件商品)

一开始你有无限的本钱 ,问走完这条街,你可以赚取最大的利益为多少?并且输出交易次数(买 卖 各为一次)

代码:

//贪心
#include<bits/stdc++.h>
using namespace std;
const int M=1e5+5;
int main()
{
  int i,j,n,m,t;
  cin>>t;
  while(t--)
  {
    cin>>n;
    int a[M];
    memset(a,0,sizeof a);
    for(i=1; i<=n; i++)
      cin>>a[i];
    long long ans=0,c=0,l,r,mi,mx;
    l=r=1;
    for(int i=1; i<=n; i++)
    {
      while(a[i]>=a[i+1]&&i<n)//低卖
        i++;
      mi=a[i],l=i;
      while(a[i]<=a[i+1]&&i<n)//高买
        i++;
      mx=a[i],r=i;
      if(mx>mi&&l<r&&r<=n) ans+=(mx-mi),c+=2;//如果有差价,则卖出 买 卖 各为一次 +=2
    }
    printf("%lld %lld\n",ans,c);
  }
}
/*

1
5
9 10 6 7 8
*/

猜你喜欢

转载自blog.csdn.net/qq_41668093/article/details/81195623