[LeetCode]123 Best Time to Buy and Sell Stock III
2015-01-06 18:17
1491 查看
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
http://blog.csdn.net/linhuanmars/article/details/23236995
http://blog.csdn.net/linhuanmars/article/details/23236995
public class Solution { public int maxProfit(int[] prices) { return maxProfit_K(prices, 2); } private int maxProfit_K(int[] prices, int K) { if (prices == null || prices.length <= 1) return 0; // See // http://blog.csdn.net/linhuanmars/article/details/23236995 // // 我们还是使用“局部最优和全局最优解法”。 // 我们维护两种量, // 一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]) // 另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。 // // 全局: global[i][j] = max(local[i][j] , global[i-1][j]) // 也就是去当前局部最好的,和过往全局最好的中大的那个 // 因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。 // // 局部: local[i][j]= max( global[i-1][j-1] + max(diff,0), // local[i-1][j] + diff), // 也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。 int days = prices.length; int[][] local = new int[days][K + 1]; // 0次 到 K次 int[][] global = new int[days][K + 1]; // 0次 到 K次 for (int j = 1 ; j <= K ; j ++) { for (int i = 1 ; i < days ; i ++) { // difference between today and yesterday int diff = prices[i] - prices[i - 1]; local[i][j] = Math.max(global[i - 1][j - 1] + Math.max(0, diff), local[i - 1][j] + diff); global[i][j] = Math.max(global[i - 1][j], local[i][j]); } } return global[days - 1][K]; } }
相关文章推荐
- leetcode || 123、Best Time to Buy and Sell Stock III
- Leetcode_123_Best Time to Buy and Sell Stock III
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- [leetcode-123]Best Time to Buy and Sell Stock III(c++)
- [leetcode] 123.Best Time to Buy and Sell Stock III
- leetcode 123 —— Best Time to Buy and Sell Stock III
- leetcode[123]Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- leetcode123---Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III - LeetCode 123
- leetcode 123 Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode123:Best Time to Buy and Sell Stock III
- leetcode解题报告:123 Best Time to Buy and Sell Stock III