代码随想录算法训练营第三十一天|455.分发饼干,376. 摆动序列,53. 最大子序和

代码随想录算法训练营第二十七天

  • 455.分发饼干
  • 376. 摆动序列
  • 53. 最大子序和

455.分发饼干

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.11
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/assign-cookies/
from typing import List


class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        length_g = len(g)
        length_s = len(s)
        g.sort()
        s.sort()
        g_i, s_j, num = 0, 0, 0
        while g_i < length_g and s_j < length_s:
            if s[s_j] >= g[g_i]:
                g_i += 1
                s_j += 1
                num += 1
            else:
                s_j += 1

        return num


if __name__ == '__main__':
    g = [1, 2]
    s = [1, 2, 3]
    ss = Solution()
    print(ss.findContentChildren(g, s))

376. 摆动序列

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.11
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/wiggle-subsequence/
from typing import List


class Solution:
    """
    极值才更新pre_diff
    """
    def wiggleMaxLength(self, nums: List[int]) -> int:
        result = 1
        pre_diff = 0
        for i in range(len(nums) - 1):
            cur_diff = nums[i + 1] - nums[i]
            if pre_diff >= 0 and cur_diff < 0 or pre_diff <= 0 and cur_diff > 0:
                result += 1
                pre_diff = cur_diff
        return result


if __name__ == '__main__':
    nums = [1,2,2,2,2,5]
    s = Solution()
    print(s.wiggleMaxLength(nums))

53. 最大子序和

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.11
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/maximum-subarray/
from math import inf
from typing import List


class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum = -inf
        length = len(nums)
        i = 0
        while i < length:
            cur_sum = nums[i]
            max_sum = max(max_sum, cur_sum)
            i += 1
            while cur_sum > 0 and i < length:
                cur_sum += nums[i]
                max_sum = max(max_sum, cur_sum)
                i += 1

        return max_sum


if __name__ == '__main__':
    pass

你可能感兴趣的:(算法,leetcode,职场和发展)