1. Lemonade Change (Leetcode Number: 860)
Count the number of different bills received from customers -> calculate the change that should be returned to the customer -> if the value of the change is bigger than $10, return $10 to the customer at first if possible, otherwise return $5 to the customer -> if the seller doesn't have enough change, return false -> repeat the same procedure for each customer, return True if the seller can always have enough change.
The parts of adding $20 dollar bills could be eliminated.
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
sum_bill, change = 0, 0
sum_5, sum_10, sum_20 = 0, 0, 0
n = len(bills)
for i in range(n):
if sum_bill >= bills[i] - 5:
if bills[i] == 5:
sum_5 += 1
elif bills[i] == 10:
sum_10 += 1
else:
sum_20 += 1
change = bills[i] -5
while change != 0:
if change >= 10 and sum_10:
change -= 10
sum_10 -= 1
elif sum_5:
change -= 5
sum_5 -= 1
else:
return False
sum_bill += 5
else:
return False
return True
2. Queue Reconstruction by Height (Leetcode Number: 406)
Solution Algorithm (Copied from Leetcode)
-
Sort people:
- In the descending order by height.
- Among the guys of the same height, in the ascending order by k-values.
-
Take guys one by one, and place them in the output array at the indexes equal to their k-values.
-
Return output array.
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
3. Minimum Number of Arrows to Burst Balloons (Leetcode Number: 452)
Sort the array first to maximize the possibility of overlapping adjacent ballons -> Mind the right edge of each overlapped ballon as we need to find the minimum value of right edge
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if len(points) == 0:
return 0
elif len(points) == 1:
return 1
points.sort(key = lambda x: x[0])
count = 0
right = -float("inf")
for i in points:
if i[0] > right:
right = i[1]
count += 1
else:
right = min(right, i[1])
return count