[LeetCode 188] Best Time to Buy and Sell Stock IV
来源:互联网 发布:苹果6手机壳淘宝 编辑:程序博客网 时间:2024/05/01 14:39
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
solution:
reference: http://blog.csdn.net/linhuanmars/article/details/23236995
global[i][j] means at day i with max j transactions, maximum profit.
local[i][j] means at day i with max j transactions, and last transaction happened at day i, maximum profit
global[i][j] = max(global[i-1][j], local[i][j]), diff means last profit.
local[i][j] = max(global[i-1][j] + max(diff,0), local[i-1][j] + diff)
public int maxProfit(int k, int[] prices) { int len = prices.length; if(k > len) return maxKProfit(prices); int[] local = new int[k+1]; int[] global = new int[k+1]; for(int i=0;i<prices.length-1;i++) { int diff = prices[i+1] - prices[i]; for(int j=k;j>=1;j--) { local[j] = Math.max(global[j-1] + Math.max(diff, 0), local[j]+diff); global[j] = Math.max(global[j], local[j]); } } return global[k]; } public int maxKProfit(int[] prices) { int res = 0; for(int i=1;i<prices.length;i++) { int diff = prices[i] - prices[i-1]; if(diff>0) res += diff; } return res; }
0 0
- LeetCode(188) Best Time to Buy and Sell Stock IV
- leetcode 188---Best Time to Buy and Sell Stock IV
- leetcode 188: Best Time to Buy and Sell Stock IV
- 188 Best Time to Buy and Sell Stock IV [Leetcode]
- [LeetCode 188] Best Time to Buy and Sell Stock IV
- LeetCode #188: Best Time to Buy and Sell Stock IV
- LeetCode 188 - Best Time to Buy and Sell Stock IV
- LeetCode 188 Best Time to Buy and Sell Stock IV
- Leetcode 188 Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock IV
- leetcode: Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV -- leetcode
- Best Time to Buy and Sell Stock IV--LeetCode
- LeetCode : Best Time to Buy and Sell Stock III & IV
- Best Time to Buy and Sell Stock IV Leetcode Java
- LeetCode: Best Time to Buy and Sell Stock IV
- LeetCode Best Time to Buy and Sell Stock IV
- [leetcode] 188.Best Time to Buy and Sell Stock IV
- SQL Server 2008 R2 清空数据库中ldf日志文件
- PythonChallenge过关斩将录-0~10关
- maxHappiness
- 设计模式学习笔记之迪米特法则
- PAT-A 1006. Sign In and Sign Out (25)
- [LeetCode 188] Best Time to Buy and Sell Stock IV
- id instancetype 区别
- LeetCode 题解(249) : Closest Binary Search Tree Value
- exits和In的区别(http://hi.baidu.com/delphi_relive/blog/item/d7c0034a49c4932208f7ef21.html)
- PHP实现验证码
- UPlayer播放器问题相关
- Linux tcpdump命令详解
- 多态 特征
- PHAsset心得