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.
算法1:动态规划
思想:dp[i]表示以nums[i]结尾的子序列的最大和。如果求dp[i + 1]时,有两种情况1)nums[i + 1],即第i + 1个数本身,2)是
d[i] + nums[i + 1],因此只要求max(nums[i + 1], d[i] + nums[i + 1])即可,边界值dp[0] = nums[0],算法时间复杂度为,
对于该类问题,动态规划是最好且容易理解的算法
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
dp = [0] * length
dp[0] = nums[0]
maxsum = dp[0]
for i in range(1, length):
if dp[i - 1] + nums[i] >= nums[i]:
dp[i] = dp[i - 1] + nums[i]
else:
dp[i] = nums[i]
if dp[i] >= maxsum:
maxsum = dp[i]
return maxsum
算法2:分治法
思想:将数组划分左右两部分,最大子序列和有三种情况,1)在左侧部分;2)在右侧部分;3)跨左右两部分
因此求得每种情况的最大值,取最大的
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.divideMethod(nums, 0, len(nums) - 1)
def divideMethod(self, nums, i, j):
if i == j:
return nums[i]
divide = (i + j) // 2
ls = nums[divide]
rs = nums[divide + 1]
sum = 0
for k in range(divide + 1, j + 1):
sum += nums[k]
if sum >= rs:
rs = sum
sum = 0
for k in range(divide, i - 1, -1):
sum += nums[k]
if sum >= ls:
ls = sum
maxSum = ls + rs
leftMaxSum = self.divideMethod(nums, i, divide)
rigthMaxSum = self.divideMethod(nums, divide + 1, j)
if leftMaxSum >= maxSum:
maxSum = leftMaxSum
if rigthMaxSum >= maxSum:
maxSum = rigthMaxSum
return maxSum