Programming Camp – Algorithm Training Camp – Day 31

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值