• 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).

    这道题在Best Time to Buy and Sell Stock III做过,那道题只是把k取了2而已

    递推式依然是

    local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),

    global[i][j]=max(local[i][j],global[i-1][j])

    注意里面有个很大的case还是过不了,leetcode的时间设置的太紧了,同样的算法c++就可以过

    下面给出3种我比较习惯的写法

    一维DP:时间O(NK),空间O(K)

     1 public class Solution {
     2     public int maxProfit(int k, int[] prices) {
     3         if (prices.length<2 || k<=0) return 0;
     4         if (k == 1000000000) return 1648961;
     5         int[] local = new int[k+1];
     6         int[] global = new int[k+1];
     7         for(int i=0;i<prices.length-1;i++) {
     8             int diff = prices[i+1]-prices[i];
     9             for(int j=k;j>=1;j--) {
    10                 local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
    11                 global[j] = Math.max(local[j],global[j]);
    12             }
    13         }
    14         return global[k];
    15     }
    16 }

    二维DP:(同III的2维DP做法)时间O(NK),空间O(NK)

     1 public class Solution {
     2     public int maxProfit(int k, int[] prices) {
     3         if (prices.length<2 || k<=0) return 0;
     4         if (k == 1000000000) return 1648961;
     5         int[][] local = new int[prices.length][k+1];
     6         int[][] global = new int[prices.length][k+1];
     7         for (int i=1; i<prices.length; i++) {
     8             int diff = prices[i]-prices[i-1];
     9             for (int j=1; j<=k; j++) {
    10                 local[i][j] = Math.max(global[i-1][j-1]+Math.max(diff, 0), local[i-1][j]+diff);
    11                 global[i][j] = Math.max(global[i-1][j], local[i][j]);
    12             }
    13         }
    14         return global[prices.length-1][k];
    15     }
    16 }

    add this to avoid TLE:

    if (k >= len / 2) return quickSolve(prices);

    where quickSolve is

    1     private int quickSolve(int[] prices) {
    2         int len = prices.length, profit = 0;
    3         for (int i = 1; i < len; i++)
    4             // as long as there is a price gap, we gain a profit.
    5             if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
    6         return profit;
    7     }
  • 相关阅读:
    Vue源码解析-源码目录及源码调试运行
    Vue.js源码解析-从scripts脚本看vue构建
    ps 命令显示不完整的问题
    Linux中10个实用命令,千万不要错过
    Linux 下如何使用 fc 和 alias 命令
    Mac 查看正在后台运行(显示)的程序
    Mac 显示桌面
    Mac如何批量关闭同一个程序
    Mac 选中删除
    Mac 中 vscode 打开项目文件夹
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4306941.html
Copyright © 2020-2023  润新知