zoukankan      html  css  js  c++  java
  • LeetCode-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.

    Analysis:

    DP formula is

    hold[i][j] = Math.max(hold[i][j-1], unhold[i][j-1]-prices[j]);

    unhold[i][j] = Math.max(unhold[i][j-1], hold[i-1][j-1]+prices[j]);

    Solution:

     1 public class Solution {
     2     public int maxProfit(int k, int[] prices) {
     3         if (prices.length<2) return 0;
     4         int len = prices.length;
     5         
     6         // IMPORTANT: you can skip calculation if you are allowed to perform the max times of transactions. 
     7         if (k>=len/2){
     8             int profit = 0;
     9             for (int i=1;i<len;i++)
    10                 if (prices[i] > prices[i-1])
    11                     profit += (prices[i] - prices[i-1]);
    12             return profit;
    13         }
    14         
    15         int[] hold = new int[len];
    16         int[] unhold = new int[len];
    17         
    18         hold[0] = -prices[0];
    19         for (int i=1;i<len;i++)
    20             hold[i] = Math.max(hold[i-1], -prices[i]);
    21 
    22         
    23         for (int i=1;i<=k;i++){
    24             int lastHold = hold[0];
    25             hold[0] = -prices[0];
    26             for (int j=1;j<len;j++){
    27                 lastHold = hold[j];
    28                 hold[j] = Math.max(hold[j-1], unhold[j-1]-prices[j]);
    29                 unhold[j] = Math.max(unhold[j-1], lastHold+prices[j]);
    30             }
    31         }
    32             
    33         return Math.max(hold[len-1],unhold[len-1]);
    34     }
    35 }
  • 相关阅读:
    Kafka API: TopicMetadata
    从事件总线和消息队列说起
    Object.defineproperty实现数据和视图的联动
    css3动画-animation
    css3动画-transition
    jquery判断对象的type
    vs如何在运行iis express调试时,不开打新窗口和关闭调试时,iis express不退出
    重写Equals的方式
    Android中包名不能大写
    C# 几种常见数据结构【转】
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5695142.html
Copyright © 2011-2022 走看看