leetCode 122. Best time to buy and sell stocks II Greedy Algorithm

122. The best time to buy and sell stocks II - LeetCode

You are given an array of integers  prices that  prices[i] represents the price of a certain stock on  i day 1.

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

Return  the maximum  profit you can make   .

Example 1:

Input: prices = [7,1,5,3,6,4]
 Output: 7
 Explanation: Buy on day 2 (stock price = 1) and sell on day 3 (stock price = 5) Out, the profit from this transaction = 5 - 1 = 4. 
     Subsequently, if you buy on the 4th day (stock price = 3) and sell on the 5th day (stock price = 6), the profit from this transaction = 6 - 3 = 3. 
     The total profit is 4 + 3 = 7.

Example 2:

Input: prices = [1,2,3,4,5]
 Output: 4
 Explanation: Buy on day 1 (stock price = 1), sell on day 5 (stock price = 5), The profit from this transaction = 5 - 1 = 4. 
     The total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1]
 Output: 0
 Explanation: In this case, the transaction cannot obtain positive profit, so the maximum profit can be obtained by not participating in the transaction, and the maximum profit is 0.

>>Ideas and analysis

  • ① Only one stock
  • ② Currently there are only operations of buying or selling stocks
  • ③ If you want to make a profit, at least two days must be a trading unit.

1. Greedy Algorithm

Let's take an example first. For example, if you buy on the 1st day (stock price = 1) and sell on the 3rd day (stock price = 10), the profit from this transaction = 10 - 1 = 9. The profit is: prices[3] - prices[1]

Equivalent to (prices[3] - prices[2]) + (prices[2] - prices[1]) 

At this time, the profit is decomposed into daily unit dimensions , instead of considering it as a whole from day 1 to day 3 !

  • Local optimum : collect daily positive profits
  • Global Optimum : Find the maximum profit

Local optimality can lead to global optimality. If you can't find a counterexample, try being greedy!

Note: There is no profit on the first day , and there will be profit at least on the second day , so the profit sequence is one day less than the stock sequence!

From the above figure, it can be seen that only daily profits are collected. The range for collecting positive profits is the stock trading range , so you only need to pay attention to the final profit and do not need to record the range. And collecting only positive profits is where greed comes in!

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result = 0;
        for (int i = 1; i < prices.size(); i++) {
            result += max(prices[i] - prices[i - 1], 0);
        }
        return result;
    }
};
  • Time complexity: O(n)
  • Space complexity: O(1)

2. Dynamic programming

class Solution {
public:
    // 动态规划 + 状态转移 时间复杂度:O(n) 空间复杂度:O(n)
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        vector<vector<int>> dp(len,vector<int>(2,0));
        dp[0][0] -= prices[0];
        dp[0][1] = 0;
        for(int i = 1;i < len; i++) {
            dp[i][0] = max(dp[i-1][0],dp[i-1][1] - prices[i]);
            dp[i][1] = max(dp[i-1][1],dp[i-1][0] + prices[i]);
        }
        return dp[len-1][1];
    }
    // 动态规划 + 状态转移 时间复杂度:O(n) 空间复杂度:O(1)
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        vector<vector<int>> dp(2,vector<int>(2));
        dp[0][0] -= prices[0];
        dp[0][1] = 0;
        for(int i = 1;i < len; i++) {
            dp[i % 2][0] = max(dp[(i-1) % 2][0],dp[(i-1) % 2][1] - prices[i]);
            dp[i % 2][1] = max(dp[(i-1) % 2][1],dp[(i-1) % 2][0] + prices[i]);
        }
        return dp[(len-1) % 2][1];
    }
};

My previous articles explain the dynamic programming of this question in detail:  leetCode 122. The best time to buy and sell stocks II dynamic programming + state transfer + state compression_Heheda( ̄▽ ̄)"'s blog-CSDN blog icon-default.png?t=N7T8https:// blog.csdn.net/weixin_41987016/article/details/133432053?spm=1001.2014.3001.5501

Reference and recommended articles and videos:

Greedy algorithms can also solve the stock problem! LeetCode: 122. The best time to buy and sell stocks II_bilibili_bilibili

Code Random Record (programmercarl.com)

Class screenshots from Code Caprice:

Guess you like

Origin blog.csdn.net/weixin_41987016/article/details/133500827