一.问题描述
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.
二.解决思路
方法一:
首先建立一个新数组sumA
sumA[i]=a[0]+a[1]+...a[i-1]+a[i]=sumA[i-1]+nums[i]
然后一个子数组和最大相当于求max(sumA[i]-sumA[j], sumA[i]) i>j
如果sumA[j]是大于0的,我们就不用减去它
方法二:
考虑一下什么情况下会子数组最大和会从一个子数组变成另一个子数组
假设一开始的最大子数组是x1到y1
之后变成了x2到y2
分析可得知,这种变化只可能是x1到x2的和小于等于0的时候才成立(可以用反证法证明,很容易)
如果x1到x2的和不<0,那么x1到y2的和大于x2到y2的和
因此我们只需要迭代,当sum<0的时候,重新记录sum,用res记录最大
题目描述有提到用更高效的分治算法,后面看到会更新
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.源码
#method1
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums)==1:return nums[0]
sumA=[]
sumA.append(nums[0])
max_sum,min_sum,rt=nums[0],nums[0],nums[0]
for i in range(1,len(nums)):
sumA.append(sumA[i-1]+nums[i])
rt=max(rt,sumA[i],sumA[i]-min_sum)
if sumA[i]
#method2
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
rt=nums[0]
sum_num=0
for num in nums:
if sum_num>=0:sum_num+=num
else:sum_num=num
rt=max(rt,sum_num)
return rt