Brush through LeetCode-Task10

This blog records the learning gained on the 10th day of the problem.

121. The best time to buy and sell stocks

Given an array, its i-th element is the price of a given stock on the i-th day.

If you are only allowed to complete one transaction at most (that is, buy and sell a stock once), design an algorithm to calculate the maximum profit you can make.

Note: You cannot sell stocks before buying them.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on the 2nd day (stock price = 1), and sell on the 5th day (stock price = 6). Maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.

The first thing that comes to mind in this question is to directly define a tandem double pointer brute force search, as follows. The time complexity is O (n 2) O(n^2)O ( n2 )For a very large prices array, a timeout error will be reported.

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        if (prices.size() < 2)
            return 0;
        int Max = 0, temp = 0;
        for (int i = 0; i < prices.size()-1; i++) {
    
    
            for (int j = i+1; j < prices.size(); j++) {
    
    
                temp = prices[j] - prices[i];
                Max  = (Max < temp)? temp : Max;
            }
        }
        return Max;
    }
};

So see comments area, do with dynamic programming, have the following relationship:
maximum benefit days before i = max {i-1 before the maximum benefit of the day, price on day i - A i-1 The minimum price of the day before}
then The C++ code is formed as follows:

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        if (prices.size() < 2)
            return 0;
        int Min = prices[0], Max = 0;
        for (int i = 0; i < prices.size(); i++) {
    
    
            Max = max(Max, prices[i] - Min);        //第i天最大值
            Min = min(prices[i], Min);              //前i-1天最小值 
        }
        return Max;
    }
};

122. The Best Time to Buy and Sell Stocks II

Given an array, its i-th element is the price of a given stock on the i-th day.

Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying and selling a stock multiple times).

Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on the 2nd day (stock price = 1), and sell on the 3rd day (stock price = 5), This exchange can make a profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3), and sell on the 5th day (stock price = 6). This exchange can make a profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1) and sell on the 5th day (stock price = 5), this The exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first and second days and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.

prompt:

1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

analysis:

  1. There is a particularly witty approach. As long as the price today is less than the price tomorrow, buy it today and sell it tomorrow, squeezing all profits. The essence is a greedy algorithm, one traversal, time complexity O (n) O(n)O ( n ) , the code is as follows:
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int ans = 0;
        for (int i = 1; i < prices.size(); i++) {
    
    
            if (prices[i] > prices[i-1]) {
    
    
                ans += prices[i] - prices[i-1];
            }
        }
        return ans;
    }
};
  1. Dynamic programming
  • There are only two states on the i day, not holding or holding stocks.
  • The status of not holding stocks may come from selling today or not holding stocks yesterday.
  • In the same way, the status of holding stocks on the day may come from buying today or holding them yesterday. Taking the status of not holding stocks on the last day is the solution to the problem.
  • This idea comes from the comment area, it is indeed very profound! I found that dynamic programming is to construct recurrence relations? [Surprise]
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int n = prices.size();
        if (n < 2)
            return 0;
        vector<vector<int>> dp;    
        for(int i = 0; i < n; i++)         //构建(n,2)二维数组,初始化为0
	        dp.push_back(vector<int>(2,0));

        // dp[i][0]表示第i天不持有股票, dp[i][1]表示第i天持有股票
        dp[0][0] = 0; dp[0][1] = -prices[0];
        for (int i = 1; i < n; 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[n-1][0];
    }
};

124. The maximum path sum in a binary tree

A path is defined as a sequence starting from any node in the tree, connecting the parent node-child node, and reaching any node. The path contains at least one node and does not necessarily pass through the root node.

The path sum is the sum of the value of each node in the path.

You root for the root node of a binary tree, returns to its maximum and path .

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3, and the path sum is 2 + 1 + 3 = 6
ex1

Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7, and the path sum is 15 + 20 + 7 = 42.
ex2
Tip:

树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000

Guess you like

Origin blog.csdn.net/qq_33007293/article/details/112975826