Leetcode之动态规划(DP)专题-123. 买卖股票的最佳时机 III(Best Time to Buy and Sell Stock III)...
2019-09-08 18:24
489 查看
原文链接:http://www.cnblogs.com/qinyuguan/p/11487720.html
Leetcode之动态规划(DP)专题-123. 买卖股票的最佳时机 III(Best Time to Buy and Sell Stock III)
股票问题:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [3,3,5,0,0,3,1,4] 输出: 6 解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。 随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:
输入: [1,2,3,4,5] 输出: 4 解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入: [7,6,4,3,1] 输出: 0 解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。
限制次数为2次。
dp[i][0][k]表示第i天不持有股票且最大交易次数为k次的最大利润。
dp[i][1][k]表示第i天持有股票且最大交易次数为k次的最大利润。
详解看其他几个股票问题。
class Solution { public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int k = 2; int[][][] dp = new int[prices.length][2][k+1]; for (int i = 0; i < k+1; i++) { dp[0][0][i] = 0; dp[0][1][i] = -prices[0]; } for (int i = 1; i < prices.length; i++) { for (int k1 = 1; k1 <= k; k1++) { dp[i][0][k1] = Math.max(dp[i-1][0][k1],dp[i-1][1][k1]+prices[i]); dp[i][1][k1] = Math.max(dp[i-1][1][k1],dp[i-1][0][k1-1]-prices[i]); } } return dp[prices.length-1][0][k]; } }
转载于:https://www.cnblogs.com/qinyuguan/p/11487720.html
相关文章推荐
- Leetcode之动态规划(DP)专题-121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)...
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- [LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- LeetCode——Best Time to Buy and Sell Stock III (股票买卖时机问题3)
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)
- 【LeetCode】Best Time to Buy and Sell Stock(买卖股票的最佳时间)
- [LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV
- Leetcode 123 Best Time to Buy and Sell Stock III 至多两次买卖股票最大收益
- LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)
- **[Lintcode]Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV Leetcode
- 【LintCode】 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】