Maximum Subarray

来源:互联网 发布:淘宝搜索热度什么意思 编辑:程序博客网 时间:2024/06/01 10:26

题目:

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.

我的解法:

(1)算法思想:

记sum=max=A[0],顺序遍历一次数组,将A[i]加到sum中,如果sum小于A[i],则用A[i]替换sum;如果sum大于max,则用sum替换max。遍历完,返回max即可。

(2)代码如下:


1 0
原创粉丝点击