O(n) Java solution...Easy to understand!!


  • 1
    A
    public class Solution {
        public int maxSubArray(int[] nums) {
            if (nums == null || nums.length == 0){
                return 0;
            }
            int max = nums[0];
            int sum = nums[0];
            for (int i = 1; i < nums.length; i++){
                sum += nums[i];
                if (sum > nums[i]){
                    sum = sum;
                }
                else {
                    sum = nums[i];
                }
                
                if (sum > max){
                    max = sum;
                }
            }
            return max;
        }
    }

Log in to reply
 

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