DW&LeetCode_day10(121、122、124)

DW&LeetCode_day10(121、122、124)


Write in front:

  • It’s the tenth day in a blink of an eye, and more than 30 questions have been written, yes, keep on!

Open source content

Open source content

table of Contents

DW&LeetCode_day10(121、122、124)

Write in front:

Open source content

Study outline 

121. The best time to buy and sell stocks

answer:

122. The Best Time to Buy and Sell Stocks II

answer:

124. The maximum path sum in a binary tree

answer:



Study outline 


121. The best time to buy and sell stocks

answer:

Take LeetCode 881 lifeboat problem as an example

Since this question only requires calculation 最小船数, whether the original array is changed or not, and the element index position are not considered, so you can sort the given array first, and then traverse from both sides of the array to the middle. So the idea of ​​solving the problem is as follows:

  1. Sort the given array in ascending order
  2. Initialize left and right pointers
  3. Each time, a "heaviest" and a "lightest" are used for pairing. If the weight of the two is less than the weight of the two Limit, the "lightest" will board the boat at this time, that is ( left++). Regardless of whether the "lightest" is on board or not, the "heaviest" must be on board, that is ( right--) and the required number of ships plus one, that is ( num++)

code show as below:

var numRescueBoats = function(people, limit) {
  people.sort((a, b) => (a - b));
  var num = 0
  let left = 0
  let right = people.length - 1
  while (left <= right) {
    if ((people[left] + people[right]) <= limit) {
      left++
    }
    right--
    num++
  }
  return num
};

Double pointer

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n < 2: return 0        #  必须有两个数字,一买一卖
        a, b = 0, 1               # 初始化两个指针    
        profit = prices[b] - prices[a]
        for i in range(1, n):
            if prices[i] - prices[a] < 0: a = i    # 卖出去是亏本的
            if prices[i] - prices[a] > profit:  profit = prices[i] - prices[a]# 卖出能获得最大利润
        return profit if profit > 0 else 0  # 最大的 profit 也有可能是负数

When you encounter an ordered array, you should first think about 双指针solving the problem, because the simultaneous traversal of two pointers will reduce the space complexity and time complexity. 

122. The Best Time to Buy and Sell Stocks II

answer:

# 买所有的上涨交易日,下跌的不买
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i-1]   # 利润累加
            if tmp > 0: profit += tmp       #判断是否亏损
        return profit 

124. The maximum path sum in a binary tree

answer:

# 通过root节点的最大路径和 
class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        self.maxL = float('-inf')
        def dfs(root): # 寻找通过root节点的最大路径和 
            if not root:return 0 # dfs的目的为能提供的最大路径和
            leftTree = dfs(root.left)
            rightTree = dfs(root.right)
            self.maxL=max(leftTree + rightTree + root.val,self.maxL) 
            return max(0,leftTree+root.val,rightTree+root.val) # 针对递归调用 由需求来决定返回值 
        dfs(root)
        return self.maxL

 

Guess you like

Origin blog.csdn.net/adminkeys/article/details/112916331