53. Maximum Subarray

53. Maximum Subarray

    My Submissions
Question Editorial Solution
Total Accepted: 111178  Total Submissions: 302914  Difficulty: Medium

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.

两种解法,分治和动态规划


1.分治算法 nlnn

思路:由于我们知道最大子序列可能存在于A数组的左边,右边,或者一点左边一点右边。 
所以我们很容易可以联想到,居然这样我们可以把A数组划分成若干个小的子数组,对子数组求出左边的最大值,和右边的最大值,再求出从中间位置到左边的某个位置的最大值、从中间位置到右边的某个位置的最大值,得到了这四个值之后剩下的我们就可以通过比较得到这个子数组的最大值了。(递归的过程) 

public class Solution {
    public int maxSum(int[] A, int left, int right )
	{
	    if( left == right ){
	        return A[left];
	    }
	    int center = (left + right) / 2;
	    int maxLeftSum  = maxSum( A, left, center);
	    int maxRightSum = maxSum( A, center+1, right);    
	    int maxLeft = Integer.MIN_VALUE, tempLeft = 0;
	    int maxRight = Integer.MIN_VALUE, tempRight = 0;
	    for (int i=center; i>=left; --i){
	    	tempLeft += A[i];
	    	if (tempLeft > maxLeft){
	    		maxLeft = tempLeft;
	    	}
	    }
	    for (int i=center+1; i<=right; ++i){
	    	tempRight += A[i];
	    	if (tempRight > maxRight){
	    		maxRight = tempRight;
	    	}
	    }	  
	    int maxCenterSum = maxLeft + maxRight;	    
	    return maxCenterSum > maxLeftSum ? (maxCenterSum > maxRightSum ? maxCenterSum : maxRightSum) : maxLeftSum > maxRightSum ? maxLeftSum : maxRightSum;
	}
	public int maxSubArray(int[] A){
		int len = A.length;
		return maxSum(A,0,len-1);
	}
}

2.动态规划,我第一个想到的。。

public int maxSubArray(int[] nums) {
       int sum=nums[0];
       int value=0;
       if(nums[0]>0){
           value=nums[0];   
       }
       for(int i=1;isum){
               sum=value;
           }
           if(value<0){
               value=0;
           }
       }
       return sum;
    }


你可能感兴趣的:([Leetcode])