波波老师好!我发现Leetcode共有如下stoclk buy and sell问题:
如果用dfs + memoization的方法,我发现可以用基本相同的思路来处理。不同的是,需要根据不同约束条件进行调整。我的问题主要在121和123题,不知道我是否遗漏了啥。对于LC 123题,我的解如下:
class Solution {
Integer[][][] memo;
public int maxProfit(int[] prices) {
memo = new Integer[prices.length][2][3];
return dfs(prices, 0, 0, 0);
}
private int dfs(int[] prices, int day, int hasStock, int times) {
if (day >= prices.length) {
return 0;
}
if (memo[day][hasStock][times] != null){
return memo[day][hasStock][times];
}
int profit = dfs(prices, day + 1, hasStock, times);
if (hasStock == 1) {
profit = Math.max(profit, dfs(prices, day + 1, 0, times + 1) + prices[day]);
} else if (times < 2) {
profit = Math.max(profit, dfs(prices, day + 1, 1, times) - prices[day]);
}
return memo[day][hasStock][times] = profit;
}
}
我的问题主要有两个:
class Solution {
public int maxProfit(int[] prices) {
int heldOne = Integer.MIN_VALUE;
int soldOne = 0;
int heldTwo = Integer.MIN_VALUE;
int soldTwo = 0;
for (int i = 0; i < prices.length; i++) {
int tempHeldOne = heldOne;
int tempSoldOne = soldOne;
int tempHeldTwo = heldTwo;
int tempSoldTwo = soldTwo;
heldOne = Math.max(tempHeldOne, -prices[i]);
soldOne = Math.max(tempSoldOne, tempHeldOne + prices[i]);
heldTwo = Math.max(tempHeldTwo, tempSoldOne - prices[i]);
soldTwo = Math.max(tempSoldTwo, tempHeldTwo + prices[i]);
}
return Math.max(soldTwo, soldOne);
}
}