Leetcode最大和最小子序和

最大子序和,动态规划时间复杂度为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\{ \begin{array} { l } { sf(x_1)+x_2, \quad sf(x_1 )+x_2 >x_2 } \\ { x_2,\quad sf(x_1) + x_2<=x_2 } \end{array} \right. 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\{ \begin{array} { l } { sf(x_2)+x_3, \quad sf(x_2) +x_3 >x_3 } \\ { x_3,\quad sf(x_2) + x_3<=x_3 } \end{array} \right. 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

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

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

猜你喜欢

转载自blog.csdn.net/herosunly/article/details/106641003