Maximum Subarray

Kadane Algorithm O(n) Not working for all negative number arrays

其实解决方案也很简单,把maxSum定为Integer.MIN_VALUE,或者maxSum=A[0]

public class Solution {
    public int maxSubArray(int[] A) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if(A.length == 0)
			return 0;
		int maxSum = A[0];
		int endSum = 0;
		for(int i = 0; i < A.length; i++){
			if(endSum >= 0)
				endSum += A[i];
			else
				endSum = A[i];
			if(maxSum < endSum)
				maxSum = endSum;
		}
		return maxSum;
	}
}


Divide and Conquer O(nlogn)

public class Solution {
    public int maxSubArray(int[] A) {
		// Start typing your Java solution below
		// DO NOT write main() function
		return find_max_subarray(A, 0, A.length - 1);
	}
	public int find_max_subarray(int[] A, int low, int high){
		if(low == high)
			return A[low];
		else{
			int mid = (low + high) / 2;
			int left_sum = find_max_subarray(A, low, mid);
			int right_sum = find_max_subarray(A, mid + 1, high);
			int cross_sum = find_max_crossing_subarray(A, low, mid, high);
			if(left_sum >= right_sum && left_sum >= cross_sum)
				return left_sum;
			else if(right_sum >= left_sum && right_sum >= cross_sum)
				return right_sum;
			else
				return cross_sum;
		}
	}
	public int find_max_crossing_subarray(int[] A, int low, int mid, int high){
		int left_sum = Integer.MIN_VALUE;
		int sum = 0;
		for(int i = mid; i >= low; i--){
			sum += A[i];
			left_sum = sum > left_sum ? sum : left_sum;
		}
		int right_sum = Integer.MIN_VALUE;
		sum = 0;
		for(int i = mid + 1; i <= high; i++){
			sum += A[i];
			right_sum = sum > right_sum ? sum : right_sum;
		}
		return left_sum + right_sum;
	}
}


你可能感兴趣的:(Maximum Subarray)