309. 买卖股票的最佳时机含冷冻期

原题链接:

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], where n is the length of the prices array.
    • Fill memories with -1 to indicate uncomputed values.
  • Return: The result of the recursive method dfs_maxProfit starting from the last day (n-1) and state 0 (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), return 0 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.
  • 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]).
    • 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]).
  • 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]);
    }

}

错误经验吸取

  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值