原题
https://leetcode.com/problems/maximum-subarray/
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
使用Kadane’s 算法, 遍历数组, 计算在i点时的最大和 max_end_here, 并更新max_so_far, https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane’s_algorithm
Time: O(n)
Space: O(1)
代码
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_end_here = max_so_far = nums[0]
for i in range(1, len(nums)):
max_end_here = max(nums[i], nums[i] + max_end_here)
max_so_far = max(max_so_far, max_end_here)
return max_so_far
解法2
动态规划, 初始化dp数组, dp[i]表示在i点最大的子数组. 状态转移方程:
dp[i] = dp[i-1] + nums[i] if dp[i-1] > 0 else nums[i]
然后我们求dp中最大的值即可.
代码
class Solution:
def maxSubArray(self, nums: 'List[int]') -> 'int':
dp = nums[:]
for i in range(1, len(nums)):
if dp[i-1] > 0:
dp[i] = dp[i-1] + nums[i]
else:
dp[i] = nums[i]
return max(dp)