1. Assign Cookies (Leetcode Number: 39)
Sort the given lists and start comparing the values of the largest elements.
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
sor_g = sorted(g)
i = len(g) - 1
sor_s = sorted(s)
j = len(s) - 1
res = 0
while j >= 0 and i >= 0:
if sor_s[j] >= sor_g[i]:
res += 1
j -= 1
i -= 1
else:
i -= 1
return res
2. Wiggle Subsequence (Leetcode Number: 376)
Remember cur_diff != 0
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
count = 1
pre_diff = 0
for i in range(len(nums) - 1):
cur_diff = nums[i + 1] - nums[i]
if cur_diff * pre_diff <= 0 and cur_diff != 0:
count += 1
pre_diff = cur_diff
return count
3. Maximum Subarray (Leetcode Number: 53)
Made a mistake of using elif for count < 0 rather than if
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
res = -float("inf")
count = 0
for i in range(len(nums)):
count += nums[i]
if count > res:
res = count
# Cannot use elif as count could be bigger than res and smaller than 0 at the same time!!!
if count <= 0:
count = 0
return res