最大子数组

来源:互联网 发布:nodejs 生成json文件 编辑:程序博客网 时间:2024/06/05 14:22

题目原型:

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.

基本思路:

令数组为A,从前往后累加得tmp,sum为最大的累加和。

1、如果A[i]>A[i]+tmp,表示,加了还不如不加,那么初始化tmp,令tmp=A[i]。若tmp>sum,则更新sum 。

2、否则,累加tmp,同时注意更新sum。

public int maxSubArray(int[] A){if(A.length==0||A==null)return 0;int sum = A[0];int tmp = A[0];for(int i = 1;i<A.length;i++){    if(A[i]>tmp+A[i]){    tmp = A[i];}else{tmp+=A[i];}if(sum<tmp)sum = tmp;}return sum;}




0 0
原创粉丝点击