LeetCode - Timing to buy and sell stocks II (Dynamic Programming)

introduce

The best time to buy and sell stocks is a high-frequency exam question. There have been many versions of this question. Especially, the best time to buy and sell stocks I and II are high-frequency exam questions in interviews. Let's take a look at how to solve them. Questions like this~

Topic description

image.png

Problem solving ideas

Whether it is the best time to buy or sell stocks I or II, dynamic programming is a good way to solve it. The most important thing for dynamic programming is to understand what the meaning of dynamic equations is. The core of dynamic programming is introduced below:

  • dp[i][0]: Indicates the maximum profit obtained on the i-th day when there is no stock in hand, that is to say, the amount of money earned.

  • dp[i][1]: Indicates the maximum profit obtained by the stock in hand on the i-th day.

  • Possibilities of dp[i][0]:

    • There is no stock in hand on day i-1: dp[i-1][0]
    • I had stock on day i-1, but I sold it today: dp[i-1][1] + prices[i]
  • Possibilities of dp[i][1]:

    • Stocks were also held the day before and held to today: dp[i-1][1]
    • No stock the day before, bought today: dp[i-1][0] - prices[i]

Dynamic programming to the last day, is it better to hold stocks or not to have stocks in hand?

手上没有股票的收益大,因为最后一天持有股票说明还没有变现。

AC code implementation

var maxProfit = function(prices) {
    
    
  // 动态规划是解决买卖股票的最佳时机的核心技巧
  // 首先构造一个二维数组dp
  const dp = new Array(prices.length).fill([0,0]);

  // 初始化
  dp[0][0] = 0;
  dp[0][1] = -prices[0];

  // 处理一般情况
  for (let i = 1; i < dp.length; i++) {
    
    
    dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1] + prices[i]);
    dp[i][1] = Math.max(dp[i-1][0] - prices[i],dp[i-1][1]);
  }

  return dp[prices.length-1][0];
};

When constructing a two-dimensional array, fill is passed in a [0,0].

What is the difference between the best time to buy and sell stocks I and the best time to buy and sell stocks II?

The core difference lies in the following line of code:

The Best Time to Buy and Sell Stocks I

dp[i][1] = Math.max(- prices[i], dp[i - 1][1]);

The Best Time to Buy and Sell Stocks II

dp[i][1] = Math.max(dp[i-1][0] - prices[i],dp[i-1][1]);

What is this indicating? The best time to buy and sell stocks If you buy today, it means that there can be no previous trading operations, that is to say, you can only buy and sell once, but the best time to buy and sell stocks II is to buy and sell multiple times.

Summarize

When encountering the same type of questions, be sure to compare the similarities and differences between the questions and carry out comparative memory.

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/123174143