Iterative Java solution. O(n) time and O(1) space complexity.


  • 0
    O
    public class Solution {
        public int maxSubArray(int[] nums) {
            if(nums.length == 1) return nums[0];
            boolean isAllNegative = true;
            int max = nums[0];
            for(int n: nums) {
                if (n > 0) isAllNegative = false;
                max = Math.max(max, n);
            }
            if(isAllNegative) return max;
            int sum = 0;
            max = 0;
            for(int n: nums) {
                sum += n;
                if(sum < 0) sum = 0;
                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.