LeetCode 53. Maximum Subarray

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.

先计算每一点的total sum,再用最大的sum - minsum
public int maxSubArray(int[] nums) {
        int min = 0, sum = 0, max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (sum - min > max) {
                max = sum - min; 
            }
            if (sum < min) {
                min = sum;
            }
        }
        return max;
    }
归纳法来解,假设每个位置i,都包含i,取一个最大值,那么每个位置的最大值可能为i本身,或者是i之前的包括i-1的最大值,max(nums[i], g(i-1)).
    public int maxSubArray(int[] nums) {
        int max = Integer.MIN_VALUE, sum = -1;
        for (int i = 0; i < nums.length; i++) {
            sum = sum > 0 ? nums[i]  + sum : nums[i];
            max = Math.max(max, sum);
        }
        return max;
    }
//这是可以返回subarray的index的版本。
public int[] maxSubArray(int[] nums) {
    int min = 0, sum = 0, max = Integer.MIN_VALUE, sindex = 0, eindex = 0, minindex = 0;
    for (int i = 0; i < nums.length; i++) {
        sum += nums[i];
        if (sum - min > max) {
            max = sum - min;
            sindex = minindex;
            eindex = i;
        }
        if (sum < min) {
            min = sum;
            minindex = i;
        }
    }
    int[] result = {max, sindex + 1, eindex};
    return result;
}
阅读更多
文章标签: leetcode
个人分类: Array substring问题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 53. Maximum Subarray

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭