1. 程式人生 > >【leetcode】123.(Hard)Best Time to Buy and Sell Stock III

【leetcode】123.(Hard)Best Time to Buy and Sell Stock III

解題思路:
DP,只是儲存的空間是O(1)
這個討論區的答案

首先buy1點是第一次買入點,對於當前點數,只有一個點數的時候只能買入,有兩個及以上的點數時可以選擇買入當前點數或者不買入當前點數即還是使用之前的點數。
sell1是第一次售出點,對於 當前點數可以選擇售出,或者不售出
buy2 sell2同理

題目限制只能有2筆交易,如果有3筆、4筆就依次加入buy3、sell3…即可


提交程式碼:

class Solution {
	public int maxProfit(int[] prices) {
		int buy1 = Integer.MIN_VALUE,
sell1 = 0; int buy2 = Integer.MIN_VALUE, sell2 = 0; for (int i = 0; i < prices.length; i++) { buy1 = Math.max(buy1, -1 * prices[i]); sell1 = Math.max(sell1, prices[i] + buy1); buy2 = Math.max(buy2, sell1 - prices[i]); sell2 = Math.max(sell2, prices[i] + buy2); } return sell2; }
}

執行結果:
在這裡插入圖片描述