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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM