• Best Time to Buy and Sell Stock IV****


    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most k transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    Analyse: Assume global[i][j] represents the maximum profit at day i with j transactions, local [i][j] is the maximum profit at day i  with j transactions at the last transaction occurred on day i. Then we have: global[i][j] = max(local[i][j], global[i - 1][j]) (the left one is doing the transaction at day i while the right one is not doing the transaction at day i), local[i][j] = max(local[i - 1][j] + diff, global[i - 1][j - 1] + max(0, diff)). (we have to do the j-th transaction on day i, so if we already did j transactions at day i - 1 and did the last transaction on the (i - 1)th day, or we did j - 1 transactions by the (i - 1)th day, then we choose the larger one. 

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int maxProfit(int k, vector<int>& prices) {
     4         if(prices.size() <= 1 || k == 0) return 0;
     5                 
     6         int result = 0;
     7         if(k >= prices.size()){//cannot do k transactions, then do all operations which can earn money
     8             for(int i = 1; i < prices.size(); i++){
     9                 if(prices[i] > prices[i - 1])
    10                     result += prices[i] - prices[i - 1];
    11             }
    12             return result;
    13         }
    14        
    15         const int n = k + 1;
    16         int l[n] = {0}, g[n] = {0};
    17         
    18         for(int i = 0; i < prices.size() - 1; i++){
    19             int diff = prices[i + 1] - prices[i];
    20             for(int j = k; j >= 1; j--){
    21                 l[j] = max(g[j - 1] + max(0, diff), l[j] + diff);
    22                 g[j] = max(l[j], g[j]);
    23             }
    24         }
    25         return g[k];
    26     }
    27 };
  • 相关阅读:
    mysql之创建数据库,创建数据表
    mysql之group by,order by
    一个人选出2门以上不及格的课程sql语句
    GIt入门
    数据库索引工作原理
    题目:50个人围城一圈数到3和3的倍数时出圈,问剩下的人是谁?原来的位置是多少?
    约瑟夫环:递归算法
    K-means算法的java实现,聚类分析681个三国武将
    java用一个for循环输出99乘法表
    写一个基于UDP协议的聊天小程序
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4746654.html
Copyright © 2020-2023  润新知