Sharing simple solution


  • 1
    P
    public class Solution {
        public int maxSubArray(int[] A) {
            if (A.length == 0) return 0;// return if length is 0
            int sum = A[0]; // assign initial value
            int maxSum = sum;//maxSum so far
            for (int i = 1; i < A.length; i++){ // loop through all the characters
                sum = (sum >= 0)? sum : 0; // if the sum drops below zero then discard the previous sum as it only going to subtract from the next sum
                sum += A[i];
                maxSum = maxSum > sum ? maxSum:sum;// check if sum is greater than maxSum
                
            }
            return maxSum;
        }
    }
    

    The code is commented


Log in to reply
 

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