【LeetCode】123. Best Time to Buy and Sell Stock III
2018-03-16 18:18
706 查看
题目描述
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 two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
参考了题解的一位大神
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39653/2ms-Java-DP-Solution
代码如下
class Solution { public int maxProfit(int[] prices) { int firstBuy = Integer.MIN_VALUE; int firstSell = 0; int secondBuy = Integer.MIN_VALUE; int secondSell = 0; for(int curPrice:prices) { secondBuy = Math.max(secondBuy,firstSell-curPrice); secondSell = Math.max(secondSell,secondBuy+curPrice); firstBuy = Math.max(firstBuy,-curPrice); firstSell = Math.max(firstSell,firstBuy+curPrice); } return secondSell; } }
相关文章推荐
- [leetcode-123]Best Time to Buy and Sell Stock III(c++)
- leetcode123---Best Time to Buy and Sell Stock III
- leetcode(121)(122)(123)(188) Best Time to Buy and Sell Stock I/II/III/IV JAVA代码
- 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
- LeetCode123 Best Time to Buy and Sell Stock III
- [Leetcode 123, Hard] 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 解题报告
- leetcode_c++:Best Time to Buy and Sell Stock III(123)
- leetcode 123. Best Time to Buy and Sell Stock III 最大k次字段和 + DP
- leetcode——123——Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III【java】
- leetcode 123 Best Time to Buy and Sell Stock III
- [Leetcode 123] Best Time to Buy and Sell Stock III
- LeetCode123:Best Time to Buy and Sell Stock III
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)