#53 Maximum Subarray

Description

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Example

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

解题思路 O(n)

从头到尾过一遍就可以得到最优解,原理是如果到目前为止的sum小于0,那他一定不在子序列里面,从0开始计数

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 0)
            return 0;
        int sum = nums[0];
        int curr = 0;
        int i;
        for(i = 0; i < nums.length; i++){
            curr += nums[i];
            if(sum < curr)
                sum = curr;
            if(curr < 0)
                curr = 0;
        }
        return sum;
    }
}

分治法

对于一个数字串来说,将它对半分成两部分,那么他的最大序列和可能出现在左侧、右侧、或者中间
左侧和右侧可以通过递归计算,中间则直接求即可

class Solution {
    public int findMax(int[] nums, int start, int end){
        if(end - start == 0)
            return nums[start];
        int leftMax;
        int rightMax;
        int mid = (start + end) / 2;
        int sum;
        leftMax = findMax(nums, start, mid);
        rightMax = findMax(nums, mid + 1, end);
        int i;
        int sum_r = Integer.MIN_VALUE;
        int sum_l = Integer.MIN_VALUE;
        int temp = 0;
        for(i = mid; i <= end; i++){
            temp += nums[i];
            if(temp > sum_r)
                sum_r = temp;
        }
        temp = 0;
        for(i = mid - 1; i >= start; i--){
            temp += nums[i];
            if(temp > sum_l)
                sum_l = temp;
        }
        if(sum_r < 0 && sum_r != Integer.MIN_VALUE)
            sum = sum_l;
        else if(sum_l < 0 && sum_l != Integer.MIN_VALUE)
            sum = sum_r;
        else
            sum = sum_r + sum_l;
        if(sum_r == Integer.MIN_VALUE){
            if(sum_l == Integer.MIN_VALUE){
                sum = Integer.MIN_VALUE;
            }
            else
                sum = sum_l;
        }
        if(sum_l == Integer.MIN_VALUE){
            if(sum_r == Integer.MIN_VALUE){
                sum = Integer.MIN_VALUE;
            }
            else
                sum = sum_r;
        }
        
        if(leftMax > rightMax && leftMax > sum){
            return leftMax;
        }
        if(rightMax > leftMax && rightMax > sum){
            return rightMax;
        }
        if(sum > leftMax && sum > rightMax){
            return sum;
        }
        return rightMax > leftMax? rightMax: leftMax;
    }
    public int maxSubArray(int[] nums) {
        return findMax(nums, 0, nums.length - 1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值