一刷 07/2022
Version #2 Better DP with two states
不是特别理解
Time O(N)
Space O(1)
class Solution {
public int maxProfit(int[] prices, int fee) {
int cash = 0;
int hold = -prices[0];
for (int i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}
}
Version #1 DP with max previous profit
Time O(N)
Space O(N)
class Solution {
public int maxProfit(int[] prices, int fee) {
int[] dp = new int[prices.length];
int prevMax = -prices[0] - fee;
// dp[i] - max profix that can achieve on day i
for (int i = 1; i < prices.length; i++) {
prevMax = Math.max(prevMax, (i >= 2 ? dp[i - 2] : 0) - prices[i - 1] - fee);
dp[i] = Math.max(dp[i - 1], prices[i] + prevMax);
}
return dp[prices.length - 1];
}
}
No comments:
Post a Comment