# 牛客多校 2018 第二场 D Money（贪心/DP）

## 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
5
9 10 7 6 8

### 输出

3 4

### 链接

https://www.nowcoder.com/acm/contest/140/D

### 题解

1、贪心。后面的商品比前面的贵的话，一定要买前面的，卖后面的。

2、在价格曲线上的连续递增的一段上，在开头买，在末尾卖肯定是最优的（利润最多，同时交易次数最少），中间多几次操作，利润是相同的

3、最多的利润，即每条递增段的头尾相减之和

4、利润最多的交易次数即连续递增段数量

### 代码

• 答案正确 89ms, 1252kb, length: 758
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 100010;
ll a[maxn];

int main()
{
int T, n;
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
ll ans = 0, cnt = 0;
bool flag = false;
for (int i = 0; i < n; ++i)
scanf("%lld", &a[i]);
for (int i = 0; i < n - 1; ++i)
{
if (a[i + 1] > a[i]) // 低买高卖
{
ans += a[i + 1] - a[i];
if (!flag) // 连续上升区间数量
cnt++;
flag = true;
}
else if (a[i + 1] < a[i])
flag = false;
}
printf("%lld %lld\n", ans, cnt * 2);
}
return 0;
}

The end.
2018-08-27 星期一