Best Time to Buy and Sell Stock IV
2015-10-02 06:21
351 查看
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.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
public class Solution { public int maxProfit(int k, int[] prices) { int len = prices.length; if (k >= len / 2) return quickSolve(prices); int[][] t = new int[k + 1][len]; for (int i = 1; i <= k; i++) { int tmpMax = -prices[0]; for (int j = 1; j < len; j++) { t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); tmpMax = Math.max(tmpMax, t[i - 1][j - 1] - prices[j]); } } return t[k][len - 1]; } private int quickSolve(int[] prices) { int len = prices.length, profit = 0; for (int i = 1; i < len; i++) // as long as there is a price gap, we gain a profit. if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; } }
相关文章推荐
- Minimum Window Substring
- Dungeon Game
- 注册和登录的测试服务器搭建
- Expression Add Operators
- Insert Interval
- Android Api Demos登顶之路(八十五)Graphics-->PurgeableBitmap
- Shortest Palindrome
- gcc与g++的区别
- *LeetCode-Longest Palindromic Substring
- 2015-2016-1 《移动平台应用开发实践》学生博客列表
- spring的配置模式与注解模式基础
- [汇编语言]debug中用r命令修改cs、ip,并不能影响a命令的代码起始写入地址?
- HtmlUnit模拟登录网站时注意事项
- [Leetcode]Letter Combinations of a Phone Number My Submissions Question Solution
- LeetCode-Simplify Path
- [LeetCode#51]N-Queens
- Log4j2使用案例
- POJ 2676 解题报告
- Wildcard matching
- my frist linux