LeetCode 53. Maximum Subarray 时间复杂度(O(n))

时间复杂度(O(n)),思想:动态更新(小于0则抛弃以前更新,大于零则累加)

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum, path_sum = float('-inf'), float('-inf')
        for num in nums:
            if path_sum <= 0: path_sum = num
            else: path_sum += num
            if max_sum < path_sum: max_sum = path_sum
        return max_sum

 

你可能感兴趣的:(LeetCode)