Leekow-122 The best time to buy and sell stocks II (dp)

Leekow-122 The best time to buy and sell stocks II

1. Topic

122. Best Time to Buy and Sell Stocks II

You are given an integer array prices, where prices[i] represents the price of a certain stock on day i .

On each day, you can decide whether to buy and/or sell stocks. You can only hold at most one share of stock at any one time . You can also buy first and sell later on the same day.

Return the maximum profit you can make.

Example 1:

输入:prices = [7,1,5,3,6,4]
输出:7
解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
     总利润为 4 + 3 = 7 。

2. Analysis

  1. topic. It can be seen that you can only hold one stock in your hand , you can buy and sell on the same day, and you can exist at the same time to find the maximum profit. This is a process of iterative traversal, and it is a process of finding the maximum value, so we can think of it as a dp array to solve.

  2. Analysis moves. There are two situations for daily stocks, one is the situation of not owning stocks on that day, and the other is the situation of owning stocks on that day.

    1. Do not own shares on the day

    • I didn’t own stocks the day before, and I didn’t operate today
    • Own stock the day before, sell it today

    2. Own stock for the day

    • Owned stock the day before, no operation today
    • Did not own stock the day before, buy today

    So we can set two states according to this, 0 means not owning stocks on that day, 1 means owning stocks on that day

  3. traverse. Since we need the state of the previous day, it is obvious that we traverse forward and backward and start traversing from the second day, so we need to initialize the value of the first day .

3. Code and comments

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        // 1. 设dp[i][0]表示在i天不持有的最大利润,dp[i][1]表示在i天持有的最大利润
        int n = prices.length;
        int[][] dp = new int[n + 1][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];

        for (int i = 1; i < n; 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[n - 1][0];

        // 2. 一维数组进行求解
        // int n = prices.length;
        // int[] dp = new int[2];

        // dp[0] = 0;
        // dp[1] = -prices[0];

        // for (int i = 1; i < prices.length; i++){
    
    
        //     dp[0] = Math.max(dp[0], dp[1] + prices[i]);
        //     dp[1] = Math.max(dp[1], dp[0] - prices[i]);
        // }
        // return dp[0];

        
    }
}

4. Practice

Link to the topic : 122. The Best Time to Buy and Sell Stocks II

Guess you like

Origin blog.csdn.net/qq_51326491/article/details/129343708