HackerRank - Stock Maximize

题目: https://www.hackerrank.com/challenges/stockmax

Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.

Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?

Input

The first line contains the number of test cases T. T test cases follow:

The first line of each test case contains a number N. The next line contains N integers, denoting the predicted price of WOT shares for the next N days.

Output

Output T lines, containing the maximum profit which can be obtained for the corresponding test case.

Constraints

1 <= T <= 10
1 <= N <= 50000

All share prices are between 1 and 100000

Sample Input

3
3
5 3 2
3
1 2 100
4
1 3 1 2

Sample Output

0
197
3

Explanation

For the first case, you cannot obtain any profit because the share price never rises.
For the second case, you can buy one share on the first two days, and sell both of them on the third day.
For the third case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.

分析:

动态规划的思想,从后往前处理,如果后面的最大值大于当前值,则将差值加到结果上,否则更新最大值。

代码:

#include <iostream>
#include <vector>

int main() {
    int T;
    std::cin >> T;
    
    int N;
    
    while(T--) {
        std::cin >> N;
        
        std::vector<int> nums(N, 0);
        for(int i = 0; i < N; ++i) {
            std::cin >> nums[i];
        }
        
        long long result = 0;  // !
        int max = nums[N - 1];
        for(int i = N - 2; i >= 0; --i) {
            if(max > nums[i]) {
                result += (max - nums[i]);
            } else {
                max = nums[i];
            }
        }
        std::cout << result << std::endl;
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值