309. 买卖股票的最佳时机含冷冻期
原题链接:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
完成情况:
解题思路:
Sure, let’s break down and explain the provided code that solves the problem of finding the maximum profit from stock trading with a cooldown period.
Problem Description
The goal is to maximize the profit from multiple stock trades, given the constraint that after selling a stock, you cannot buy a stock the next day (cooldown period of 1 day). Additionally, you cannot engage in multiple transactions simultaneously.
Solution Explanation
The solution uses dynamic programming with memoization to efficiently compute the maximum profit.
Code Breakdown
Class Definition and Instance Variables
package leetcode板块;
import java.util.Arrays;
public class _309买卖股票的最佳时机含冷冻期 {
private int[] prices;
private int[][] memories;
- Class
_309买卖股票的最佳时机含冷冻期
: This class defines the solution. - Instance Variables:
prices
: Array of stock prices.memories
: 2D array used for memoization to store intermediate results, avoiding recomputation.
maxProfit
Method
public int maxProfit(int[] prices) {
this.prices = prices;
int n = prices.length;
memories = new int[n][2];
for (int i = 0; i < n; i++) {
Arrays.fill(memories[i], -1); // -1 indicates uncomputed values.
}
return dfs_maxProfit(n - 1, 0);
}
- Parameters:
prices
(an array of stock prices). - Initialization:
- Assign the input
prices
to the instance variable. - Initialize
memories
array with dimensions[n][2]
, wheren
is the length of theprices
array. - Fill
memories
with-1
to indicate uncomputed values.
- Assign the input
- Return: The result of the recursive method
dfs_maxProfit
starting from the last day (n-1
) and state0
(not holding stock).
dfs_maxProfit
Method
private int dfs_maxProfit(int i, int hold) {
if (i < 0) return hold == 1 ? Integer.MIN_VALUE / 2 : 0;
if (memories[i][hold] != -1) return memories[i][hold];
if (hold == 1) {
return memories[i][hold] = Math.max(dfs_maxProfit(i - 1, 1), dfs_maxProfit(i - 2, 0) - prices[i]);
}
return memories[i][hold] = Math.max(dfs_maxProfit(i - 1, 0), dfs_maxProfit(i - 1, 1) + prices[i]);
}
}
- Parameters:
i
: The day index.hold
: The state of holding stock (1
if holding,0
if not).
- Base Case:
- If
i < 0
(before the first day), return0
if not holding stock (hold == 0
) or a large negative value (Integer.MIN_VALUE / 2
) if holding stock, as holding stock before any day is invalid.
- If
- Memoization Check: Return the stored value if already computed.
- Recursive Case:
- If
hold == 1
(holding stock):- Two choices: continue holding (
dfs_maxProfit(i - 1, 1)
) or sell the stock (dfs_maxProfit(i - 2, 0) - prices[i]
).
- Two choices: continue holding (
- If
hold == 0
(not holding stock):- Two choices: continue not holding (
dfs_maxProfit(i - 1, 0)
) or buy stock (dfs_maxProfit(i - 1, 1) + prices[i]
).
- Two choices: continue not holding (
- If
- Memoization Update: Store the result of the recursive computation in
memories[i][hold]
.
Summary
- The solution uses a recursive approach with memoization to avoid redundant computations.
- It considers two states for each day: holding or not holding a stock.
- It includes the cooldown period constraint by skipping a day when selling a stock.
- The memoized results are stored in the
memories
array to optimize the computation.
参考代码:
_309买卖股票的最佳时机含冷冻期
package leetcode板块;
import java.util.Arrays;
public class _309买卖股票的最佳时机含冷冻期 {
private int [] prices;
private int [][] memories;
/**
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
// 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
// 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
// 可以进行多次买入卖出,求最大利润
// TODO 最重要的就是考虑隔一天,因此需要把间距拉大一格
this.prices = prices;
int n = prices.length;
memories = new int[n][2];
for (int i = 0;i<n;i++){
Arrays.fill(memories[i],-1); // -1表示还从没有计算过
}
return dfs_maxProfit(n-1,0);
}
/**
*
* @param i
* @param hold
* @return
*/
private int dfs_maxProfit(int i, int hold) {
if (i < 0) return hold == 1 ? Integer.MIN_VALUE / 2 : 0;
if (memories[i][hold] != -1 ) return memories[i][hold];
if (hold == 1){
return memories[i][hold] = Math.max(dfs_maxProfit(i-1,1),dfs_maxProfit(i-2,0) - prices[i]);
}
return memories[i][hold] = Math.max(dfs_maxProfit(i-1,0),dfs_maxProfit(i-1,1) + prices[i]);
}
}