Accepted O(n) Solution - Java


  • 0
    L

    Basic idea, keep tracking current max and compare it with final max.

    public int maxSubArray(int[] A) {
                if(A == null || A.length == 0)
                	return 0;
                
                int temp = A[0];
                int max = temp;
                for(int i = 1; i < A.length; i++) {
                	
                	if(temp < 0) 
                		temp = A[i];
                	else 
                		temp += A[i];
                	max = Math.max(max, temp);
                }
                return max; 
        }

  • 0
    L

    oh my god. nice


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.