链接:https://www.nowcoder.com/acm/contest/140/D
来源:牛客网
题目描述
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
代码:
#include <iostream>
#include<cstdio>
using namespace std;
long long a[101000]; //int 会溢出
int main(int argc, char const *argv[]){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int flag = 1;
long long sum = 0;
long long count = 0;
scanf("%lld",&a[1]);
for (int i = 2; i <= n; ++i){
scanf("%lld",&a[i]);
if(a[i] < a[i-1]){ //出现后面比前面小的情况就计算一下前面的情况
if(a[i- 1] == a[flag]){ //如果a[i- 1] == a[flag]说明不用交易
flag = i;//更新flag
continue;
}
else{ //否则需要交易
sum += a[i- 1] - a[flag];
flag = i;
count ++;
}
}
}
if(a[n] > a[flag]){ //如果最后的数比前面的数大,前面会漏算,单独处理
sum += a[n] - a[flag];
count ++;
}
cout << sum << " " << count * 2<< endl;
}
return 0;
}