LeetCode 100 Maximum Subarray

来源:互联网 发布:vm虚拟机没有网络 编辑:程序博客网 时间:2024/05/16 04:25
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.

分析:

因为这里不要求返回数组下标,可以通过一趟遍历来把所有元素相加,当和小于0的时候,舍弃之前所有。

这里是一个O(n)的解法。

public class Solution {    public int maxSubArray(int[] A) {        int sum = 0;        int maxSum = Integer.MIN_VALUE;        for(int i=0; i<A.length; i++){            sum += A[i];            maxSum = Math.max(maxSum, sum);            if(sum < 0)                sum=0;        }        return maxSum;    }}


0 0
原创粉丝点击