1.问题描述
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.
2.解决思路
O(n)的解决方式可以参考https://en.wikipedia.org/wiki/Maximum_subarray_problem
即Kadane‘s algorithm算法,这个算法将求解最大子序列和拆分为以下两步:
1、求出数组中某一个元素 A[i] 作为最大子数列的末尾元素时, 可以找到的最大子序列的求和的值
2、取这些值中最大的那个值
其中,数组中某一个元素 A[i] 作为最大子数列的末尾元素时,可以找到的最大子序列的求和的值,应当是以A[i-1]作为最大子序列的末尾元素时可以找到的最大子序列的求和的值、A[i]两个值中较大的那一个。
3.python 2代码示例
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
else:
prefix_max = max_sum = nums[0]
for val in nums[1:]:
prefix_max = max(val, prefix_max+val)
max_sum = max(max_sum,prefix_max)
return max_sum