Java Solution Time: O(N) Space: O(1)


  • 0
    public class Solution {
        public int maxSubArray(int[] nums) {
            int res = Integer.MIN_VALUE;
            int minSoFar = 0;
            for (int i = 0; i < nums.length; i++) {
                if (i != 0) {
                    nums[i] += nums[i - 1];    
                }
                res = Math.max(nums[i] - minSoFar, res);
                minSoFar = Math.min(minSoFar, nums[i]);
            }
            return res;
        }
    }
    

    In order to make it more readable

    first, computer every subarray total[0 ~ i]
    Then iterate the array to find the max subarray which end at idx i;
    they are all candidate, so the result must be in them, return the maximum;

    public class Solution {
        public int maxSubArray(int[] nums) {
            for (int i = 1; i < nums.length; i++) {
                nums[i] += nums[i - 1];
            }
            int res = Integer.MIN_VALUE;
            int minSoFar = 0;
            for (int i = 0; i < nums.length; i++) {
                res = Math.max(nums[i] - minSoFar, res);
                minSoFar = Math.min(minSoFar, nums[i]);
            }
            return res;
        }
    }
    

Log in to reply
 

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