TLP-Task10 study notes


This article is the 21st LeetCode selected topic group Task10 study notes of the Datawhale team study plan.
For beginners, time is a bit rushed, many solutions are not analyzed in detail, and may be revised in the future, forgive me.
Datawhale learning document:
https://github.com/datawhalechina/team-learning-program/tree/master/LeetCodeTencent

121 The Best Time to Buy and Sell Stocks

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

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 get.
Note: You cannot sell stocks before buying them.

Example:

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.

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

Ideas

The idea of ​​a traversal in the official solution:
On the i-th day, if you decide to sell on that day, you must find the lowest point in history to buy in the previous days . The price is recorded with minprice.
If you plan to sell stocks on the i-th day, the maximum profit must be bought at the lowest point between [0, i-1], and record with maxprofit;
traverse the array and find what you can get when you sell (i) every day Maximum difference, and update the historical lowest price, the maximum value of profit is taken at the end of traversal.

Python implementation

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        inf = int(1e9)
        minprice = inf  # 历史最低买入价格
        maxprofit = 0   # 第i天卖出时能获得的最大利润
        for i in prices:
            maxprofit = max(i - minprice, maxprofit)    # 遍历找到最大利润
            minprice = min(i, minprice)                 # 更新历史最低价格
        return maxprofit
        

122 The Best Time to Buy and Sell StocksⅡ

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-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

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.

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.

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

Ideas

For the collection of stock questions, please refer to the series of general solutions for stock problems (reprinted and translated
) Two common algorithms for this question: dynamic programming (more general) and greedy algorithm (somewhat special).
Greedy algorithm: local optimal solution → global optimal solution

  • The "greedy algorithm" is the same as the "dynamic programming" and "backtracking search" algorithms. To accomplish one thing, it is a step-by-step decision;
  • The "greedy algorithm" always makes the best choice at each step. I understand the meaning of the two words "best" in this way:
    "Best" often means according to the topic, which may be " "Minimum" or "Maximum";
    Compared with dynamic programming, greedy algorithm does not look at the front (that is, it does not need to transfer from the previous state) or the back (no aftereffect, the latter The choice will not affect the previous choice), so the time complexity of the greedy algorithm is generally linear, and the space complexity is a constant level;
  • The "greedy" question is that for "today's stock price-yesterday's stock price", there are 3 possible results: ① positive number, ② 000, ③ negative number. The decision of the greedy algorithm is to add only positive numbers .

Author: liweiwei1419
link: https: //leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/tan-xin-suan-fa-by-liweiwei1419-2/

Python implementation

(Datawhale learning document)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        earn = 0
        for i in range(0, len(prices) - 1):
            earn += max(prices[i + 1] - prices[i], 0)
        return earn

124 Maximum path sum in binary tree

Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-tree-maximum-path-sum

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 includes at least one node, and not necessarily through the root node.
The path sum is the sum of the value of each node in the path.
Give you the root node root of a binary tree and return its maximum path sum.

Example:

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

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

prompt:

The range of the number of nodes in the tree is [1, 3 * 10^4]
-1000 <= Node.val <= 1000

Ideas

For any node, if the maximum sum path contains the node, then there are only two possible cases:
the one with the larger path value in the left and right subtrees plus the value of the node and backtracking to the parent node to form the maximum path .
The left and right subtrees are in the maximum path, and the value of this node constitutes the final maximum path.

Recursive thinking in the official solution :

First, consider implementing a simplified function maxGain(node), which calculates the maximum contribution value of a node in the binary tree,

Specifically, it is to find a path with the node as the starting point in the subtree with the node as the root node, so that the sum of the node values ​​on the path is the largest.
The calculation of this function is as follows:

  • The maximum contribution value of an empty node is equal to zero.
  • The maximum contribution value of a non-empty node is equal to the sum of the maximum contribution value of the node value and its child nodes (for leaf nodes, the maximum contribution value is equal to the node value).

Consider the contribution value of leaf nodes first, and then consider non-leaf nodes

For example, consider the following binary tree.
Insert picture description here

The maximum contribution values ​​of leaf nodes 9, 15, and 7 are 9, 15, and 7, respectively.
Then calculate the maximum contribution value of the non-leaf node. The maximum contribution value of node 20 is equal to 20+max(15,7)=35, and the maximum contribution value of node -10 is equal to -10+max(9,35)=25.

The above calculation process is a recursive process. Therefore, the maximum contribution value of each node can be obtained by calling the function maxGain on the root node.

The maximum path of the binary tree and

For a node in a binary tree, the maximum path sum of the node depends on the value of the node and the maximum contribution value of the left and right child nodes of the node. If the maximum contribution value of the child node is positive, it is included in the maximum path sum of the node , Otherwise it will not be counted as the maximum path sum of the node. Maintain a global variable maxSum to store the maximum path sum, update the value of maxSum in the recursive process, and the final maxSum value is the maximum path sum in the binary tree.

Python implementation

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.maxSum = float("-inf")

    def maxPathSum(self, root: TreeNode) -> int:
        def maxGain(node):
            if not node:
                return 0

            # 递归计算左右子节点的最大贡献值
            # 只有在最大贡献值大于 0 时,才会选取对应子节点
            leftGain = max(maxGain(node.left), 0)
            rightGain = max(maxGain(node.right), 0)
            
            # 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
            priceNewpath = node.val + leftGain + rightGain
            
            # 更新答案
            self.maxSum = max(self.maxSum, priceNewpath)
        
            # 返回节点的最大贡献值
            return node.val + max(leftGain, rightGain)
   
        maxGain(root)
        return self.maxSum

# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/solution/er-cha-shu-zhong-de-zui-da-lu-jing-he-by-leetcode-/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/cosima0/article/details/112972877