首页 > 其他 > 详细

Leetcode: Best Time to Buy and Sell Stock IV

时间:2015-03-01 13:11:38      阅读:274      评论:0      收藏:0      [点我收藏+]
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:

 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做法)

 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 }

二维DP:(local[i][j]表示前i天,即0到(i-1)th day)

 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+1][k+1];
 6         int[][] global = new int[prices.length+1][k+1];
 7         for (int i=2; i<=prices.length; i++) {
 8             for (int j=1; j<=k; j++) {
 9                 local[i][j] = Math.max(global[i-1][j-1]+Math.max(prices[i-1]-prices[i-2], 0), local[i-1][j]+(prices[i-1]-prices[i-2]));
10                 global[i][j] = Math.max(global[i-1][j], local[i][j]);
11             }
12         }
13         return global[prices.length][k];
14     }
15 }

 

Leetcode: Best Time to Buy and Sell Stock IV

原文:http://www.cnblogs.com/EdwardLiu/p/4306941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!