Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Time:O(N)Space:O(N)
1 class Solution: 2 def maxSubArray(self, nums: List[int]) -> int: 3 if nums is None or len(nums) == 0: 4 return 5 6 sum_arr = [0] * len(nums) 7 sum_arr[0] = nums[0] 8 max_res = nums[0] 9 for i in range(1, len(nums)): 10 if sum_arr[i - 1] > 0: 11 sum_arr[i] = nums[i] + sum_arr[i - 1] 12 else: 13 sum_arr[i] = nums[i] 14 max_res = max(max_res, sum_arr[i]) 15 return max_res
原文地址:https://www.cnblogs.com/xuanlu/p/11668980.html
时间: 2024-10-29 16:22:27