7-line Accepted Java O(n) solution


  • 0
    H
    public int maxSubArray(int[] nums) {
    	int res = nums[0], sum = nums[0];
    	for (int i = 1; i < nums.length; i++) {
    		if (sum < 0 && sum < nums[i]) sum = nums[i]; 
    		else sum += nums[i];
    		if (sum > res) res = sum;
    	}
    	return res;
    }

  • 0
    A

    if (sum < 0 && sum < nums[i]) sum = nums[i];

    sum < nums[i] check seem like is redundant, with

    if (sum > res) res = sum;


  • 0
    H

    You mean you want to remove "sum < nums[i]"? It wouldn't work since 'sum' might be bigger than 'nums[i]', "sum = nums[i]" would make 'sum' smaller.


Log in to reply
 

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