leetcode 53. Maximum Subarray (分治法)

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

Example:

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

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.


思路:O(n)方法很普通,O(nlog n)的分治法参考了https://blog.csdn.net/xshengh/article/details/12708291 的分治法思路,一个子串的最大和 是其左子串最大和,右子串最大和,还有包含中间数的最大和(要计算,这是关键一步),三者的最大和。根据这种思路分治,关键是合并这一步,计算包含中间那个数的最大和。

class Solution {
    public int maxSubArray(int[] nums) {
        return divide(nums,0,nums.length-1);
    }
    public int divide(int[] nums,int start,int end){
        if(start>=end) return nums[start];//大于的情况就当是中间情况了
        int mid=(start+end)/2;
        int maxleft=divide(nums,start,mid-1);//左边最大和
        int maxright=divide(nums,mid+1,end);
        //计算包含中间的连续最大和
        int midl=nums[mid];        
        for(int temp=mid-1,sum=nums[mid];temp>=start;temp--){//计算左边
            sum+=nums[temp];
            midl=midl>sum?midl:sum;
        }
        int midr=midl;
        for(int temp=mid+1,sum=midr;temp<=end;temp++){//计算右边
            sum+=nums[temp];
            midr=midr>sum?midr:sum;
        }
        return Math.max(maxleft,Math.max(maxright,midr));//最大子串在左边,最大子串在右边,或者包含中间那个数
    }
}

阅读更多
个人分类: leetcode and lintcode
想对作者说点什么? 我来说一句

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

关闭
关闭
关闭