Leetcode最大和最小子序和

举报
herosunly 发表于 2021/11/19 01:18:58 2021/11/19
【摘要】 最大子序和,动态规划时间复杂度为O(n),则假设每一步为step, s ...

最大子序和,动态规划时间复杂度为O(n),则假设每一步为step,
s f ( x 1 ) = x 1 sf(x_1)=x_1 sf(x1)=x1

s f ( x 2 ) = { s f ( x 1 ) + x 2 , s f ( x 1 ) + x 2 > x 2 x 2 , s f ( x 1 ) + x 2 < = x 2 sf (x_2 ) = \left\{

sf(x1)+x2,sf(x1)+x2>x2x2,sf(x1)+x2<=x2 s f ( x 1 ) + x 2 , s f ( x 1 ) + x 2 > x 2 x 2 , s f ( x 1 ) + x 2 <= x 2
sf(x2)={sf(x1)+x2,sf(x1)+x2>x2x2,sf(x1)+x2<=x2

s f ( x 3 ) = { s f ( x 2 ) + x 3 , s f ( x 2 ) + x 3 > x 3 x 3 , s f ( x 2 ) + x 3 < = x 3 sf (x_3 ) = \left\{

sf(x2)+x3,sf(x2)+x3>x3x3,sf(x2)+x3<=x3 s f ( x 2 ) + x 3 , s f ( x 2 ) + x 3 > x 3 x 3 , s f ( x 2 ) + x 3 <= x 3
sf(x3)={sf(x2)+x3,sf(x2)+x3>x3x3,sf(x2)+x3<=x3

f ( x 1 , x 2 ) = m a x ( s f ( x 1 ) , s f ( x 2 ) ) f(x_1, x_2) = max(sf(x_1), sf(x_2)) f(x1,x2)=max(sf(x1),sf(x2))

f ( x 1 , x 2 , x 3 ) = m a x ( s f ( x 1 ) , s f ( x 2 ) , s f ( x 3 ) ) f(x_1, x_2,x_3) = max(sf(x_1), sf(x_2), sf(x_3)) f(x1,x2,x3)=max(sf(x1),sf(x2),sf(x3))

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0

        global_max = nums[0]
        step_max = nums[0]

        if len(nums) == 1:
            return global_max

        for i in range(1, len(nums)):
            if step_max + nums[i] < nums[i]:
                step_max = nums[i]
            else:
                step_max += nums[i]

            if step_max > global_max:
                global_max = step_max

        return global_max


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
class Solution:
    def minSubArray(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0

        global_min = nums[0]
        step_min = nums[0]

        if len(nums) == 1:
            return global_min

        for i in range(1, len(nums)):
            if step_min + nums[i] < nums[i]:
                step_min += nums[i]
            else:
                step_max = nums[i]

            if step_min < global_min:
                global_min = step_min

        return global_min

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

https://www.zhihu.com/question/23995189/answer/35324479
https://www.zhihu.com/question/52165201

文章来源: blog.csdn.net,作者:herosunly,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/herosunly/article/details/106641003

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。