zoukankan      html  css  js  c++  java
  • Hackerrank--Stock Maximize(DP Practice)

    题目链接

    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.

    经典的dp题目,每天可以买进一份股票,或者卖出任意份的股票(当然你要有这么多份股票),或者什么也不做。

    首先,如果你在某一天买一份股票,那么这一天的股票价格一定不是从当天起到最后一天的最大值,想一想。

    其次,如果选择在某一天卖出若干份股票,那么一定是将所有的股票都卖出才是最优策略。

    最后,如果选择在某一天卖出股票,那么当天的股票价格一定是从当天起到最后一天的最大值。

    Accepted Code:

     1 #include <iostream>
     2 using namespace std;
     3 
     4 typedef long long LL;
     5 const int maxn = 50002;
     6 int a[maxn];
     7 
     8 int main(void) {
     9     ios::sync_with_stdio(false);
    10     int T;
    11     cin >> T;
    12     while (T--) {
    13         int n;
    14         cin >> n;
    15         for (int i = 1; i <= n; i++) cin >> a[i];
    16         int max_price = -1;
    17         LL ans = 0;
    18         for (int i = n; i >= 1; i--) {
    19             max_price = max(max_price, a[i]);
    20             ans += max_price - a[i];
    21         }
    22         cout << ans << endl;
    23     }
    24     
    25     return 0;
    26 }
  • 相关阅读:
    C#泛型类的简单创建与使用
    线程、委托、lambda运算符的简单示例
    异步编程中使用帮助类来实现Thread.Start()的示例
    C#操作INI配置文件示例
    C#“简单加密文本器”的实现
    Java设计模式之模板模式(Template )
    java提取出一个字符串里面的Double类型数字
    阿里云服务器配置SSL证书成功开启Https(记录趟过的各种坑)
    Gson解决字段为空是报错的问题
    shiro 单点登录原理 实例
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3917371.html
Copyright © 2011-2022 走看看