Monday, March 4, 2013

[LeetCode] Maximum Subarray

Thought:
Divide and Conquer.

Code:
public class Solution {
    public int maxSubArray(int[] A) {
        return max(A, 0, A.length - 1);
    }
    public int max(int[] A, int start, int end) {
        if (start > end) return Integer.MIN_VALUE;
        int mid = (start + end) / 2;
        int max1 = max(A, start, mid - 1);
        int max2 = max(A, mid + 1, end);
        int tmp = 0, max31 = 0, max32 = 0;
        for (int i = mid - 1; i >= start; i--) {
            tmp = tmp + A[i];
            max31 = Math.max(max31, tmp);
        }
        tmp = 0;
        for (int j = mid + 1; j <= end; j++) {
            tmp = tmp + A[j];
            max32 = Math.max(max32, tmp);
        }
        int max3 = max31 + max32 + A[mid];
        return Math.max(max1, Math.max(max2, max3));
    }
}

No comments:

Post a Comment