Thursday, January 8, 2015

LeetCode 53: 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.
public class Solution {
    public int maxSubArray(int[] A) {
        int n = A.length;
        
        if (n == 0)
            return 0;
            
        if (n == 1)
            return A[0];
            
        int currentMax = A[0]; // Current Max
        int max = A[0]; 
        
        for (int i = 1; i < n; i++)
        {
            currentMax = Math.max(currentMax+A[i], A[i]);
            max = Math.max(max, currentMax);
        }
        
        return max;
    }
}

No comments:

Post a Comment