Programming Camp – Algorithm Training Camp – Day 37

1. Monotone Increasing Digits (Leetcode Number: 738)

Made a mistake of the indentation of the break statement

class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        if n < 10:
            return n
        
        st_n = list(str(n))
        
        for i in range(len(st_n) - 1, 0, -1):
            if int(st_n[i]) < int(st_n[i - 1]):
                st_n[i - 1] = str(int(st_n[i -1]) -1)
                st_n[i] = "9"
        
        for j in range(len(st_n)):
            if st_n[j] == "9":
                # the following for loop could be replaced with a[j:] = '9' * (len(a) - j)
                for k in range(j, len(st_n)):
                    st_n[k] = "9"
                break
        
        return int("".join(st_n))

2. Best Time to Buy and Sell Stock with Transaction Fee (Leetcode Number: 714)

Start from the beginning, find the minimum price min_price to start buying the stock -> check the value of each element and lock the profit when the value of prices[i] is larger than min_price + fee -> within the same statement, change the min_price to prices[i] - fee in case the following value still goes even larger or not small enough to cover the paid fee.

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        res = 0
        min_price = prices[0]
        
        for i in range(1, len(prices)):
            if prices[i] < min_price:
                min_price = prices[i]
            elif prices[i] >= min_price and prices[i] <= min_price + fee:
                continue
            else:
                res += prices[i] - min_price - fee
                min_price = prices[i] - fee
        return res

3. Binary Tree Cameras (Leetcode Number: 968) ***

Copied from the answer, will try to finish this next time by myself

class Solution(object):
    def minCameraCover(self, root):
        res = 0
        
        def post_order_dfs(root):
            nonlocal res
            
            if not root:
                return 2
            left = post_order_dfs(root.left)
            right = post_order_dfs(root.right)
            
            if left == 2 and right == 2:
                return 0
            
            elif left == 0 or right == 0:
                res += 1
                return 1
            
            elif left == 1 or right == 1:
                return 2
        
        if post_order_dfs(root) == 0:
            res += 1
        
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值