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.

解题思路
本问题是一个最大子串和问题,利用Kadane算法解决,时间复杂度为O(n)。但是在解决本题时需要注意Kadane算法只能解决有正数时的问题,因此还需要考虑全是负数的场景。具体Kadane算法思路见 http://blog.csdn.net/joylnwang/article/details/6859677

源代码
package leetcode;

public class MaximumSubarray {
	public int maxSubArray1(int[] A) {//此方法超时,不适用
		int length = A.length;
		int sum = A[0];
		for(int i = 0; i < length; i++){
			int temp = A[i];
			if(temp > sum) sum = temp;
			for(int j = i + 1; j < length; j++){
				temp += A[j];
				if(temp > sum) sum = temp;
			}
		}
        return sum;
    }
	public int maxSubArray(int[] A){
		//判断是否全是负数,如果不是全为负数,则可以使用Kadane算法
		boolean allNegative = true;
		for(int i = 0; i < A.length; i++){
			if(A[i] > 0) {allNegative = false;break;}
		}
		if(allNegative){
			int returns = A[0];
			for(int i = 0; i < A.length; i++){
				if(A[i] > returns) returns = A[i];
			}
			return returns;
		}
		
		//Kadane算法
		int left, right, curLeft, curRigth, max, curMax;
		left = 0;
		right = 0;
		curLeft = 0;
		curRigth = 0;
		max = A[0];
		curMax = 0;
		for(int i = 0; i < A.length; i++){
			curMax += A[i];
			if(curMax > 0){
				curRigth = i;
				if(curMax > max){
					max = curMax;
					left = curLeft;
					right = curRigth;
				}
			}
			else{
				curMax = 0;
				left = i + 1;
				right = i + 1;
			}
		}
		return max;
	}
	
	public static void main(String[] args) {
		//int[] A = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
		int[] A = {-2, -1};
		MaximumSubarray ms = new MaximumSubarray();
		System.out.println(ms.maxSubArray(A));
	}
}

你可能感兴趣的:(array)