Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
一开始比较难想到最简洁的算法。写得很挫。后来找到了简洁的办法。
max_sum 必然是以A[i](取值范围为A[0] ~ A[n-1])结尾的某段构成的,也就是说max_sum的candidate必然是以A[i]结果的。如果遍历每个candidate,然后进行比较,那么就能找到最大的max_sum了。
假设把A[i]之前的连续段叫做sum。可以很容易想到:
如果sum>=0,就可以和A[i]拼接在一起构成新的sum’。因为不管A[i]多大,加上一个正数总会更大,这样形成一个新的candidate。
反之,如果sum<0,就没必要和A[I]拼接在一起了。因为不管A[i]多小,加上一个负数总会更小。此时由于题

这篇博客介绍了如何解决LeetCode中的53题——找到数组中具有最大和的连续子数组。通过动态规划的方法,作者阐述了如何找到以每个元素结尾的最大子数组和,并解释了当遇到负数时如何决定是否继续累加。在循环过程中,不断更新最大子数组和,从而得到最终答案。此外,还提到了使用分治策略的另一种解法。
订阅专栏 解锁全文
159

被折叠的 条评论
为什么被折叠?



