53. Maximum Subarray

隐身守侯 提交于 2020-08-18 08:45:08

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.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution

Approach 1: o(n)

 

currSum = max(nums[i], currSum+nums[i])   # The maximum value before the nums[i]

maxSum = max(currSum, maxSum)   #previous maximum

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        currSum = nums[0]
        maxSum = nums[0];
        i = 1
        while(i < len(nums)):
            currSum = max(nums[i], currSum+nums[i])
            maxSum = max(currSum, maxSum)
            print(currSum, maxSum)
            i += 1
        return maxSum

Approach 2: the divide and conquer approach

...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!