Best O(n) solution and O(1) space in java


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

Log in to reply
 

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