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