Java very simple solution to understand


  • 1

    Check if the current sum is greater than max sum. If the sum somehow reached negative reset it to 0 as it will only decrease the sum.

    public int maxSubArray(int[] nums) {
            int maxSum = Integer.MIN_VALUE;
            int sum = 0;
            for (int i = 0; i < nums.length; i++) {
                sum = sum + nums[i];
                if(sum > maxSum){
                    maxSum = sum;
                }
                if(sum < 0){
                    sum = 0;
                }
            }
    
            return maxSum;
        }
    

Log in to reply
 

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