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.

题意:给一个数组,求连续的子数组,加和最大,输出和

思路:自己想的要从连续的1个到n个遍历n遍数组才能找到连续的子数组的最大总和。
答案是,假设已经知道nums[0]…nums[i-1]的最大总和,如何将其扩展为nums[0]…nums[i]的最大总和?此时令maxSoFar为nums[0]…nums[i-1]的最大总和,numsEnding为以nums[i]为结尾的子数组(一定包括了nunms[i])的最大总和。结果自然是maxEnding和maxSoFar的较大值。
那么如何确定maxEnding呢?
MaxEnding是nums[i]加上之前的MaxEnding,或者只是nums[i],取较大值。

public static int maxSubArray(int[] A) {
    int maxSoFar=A[0];
    int maxEnding=A[0];
    for (int i=1;i<A.length;++i){
    	maxEnding= Math.max(maxEnding+A[i],A[i]);
    	maxSoFar=Math.max(maxSoFar, maxEnding);	
    }
    return maxSoFar;
}

你可能感兴趣的:(leetcode)