Maximum Subarray – LeetCode 53
Problem
Description
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
Example
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
Answer
Original
Code
1 | class Solution { |
思路
这里使用动态规划,curSum保存局部最优解,res保存全局最优解。在curSum部分,选择当前值和累加值,意味着若累加值不能给当前值带来贡献则舍弃。这样将在一次遍历中生成所有局部最优解,然后通过res进行记录,最后返回答案。时间复杂度$O(n)$,空间复杂度$O(1)$。
Better
思路
更多的可以在Wiki看到