Last active
November 13, 2017 17:28
-
-
Save shailrshah/e3ec2bfaec17a8b8e3536ef80d7de39d to your computer and use it in GitHub Desktop.
Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int maxSubArray(int[] nums) { | |
if(nums.length == 0) return 0; | |
int localMax = nums[0]; | |
int globalMax = localMax; | |
for(int i = 1; i < nums.length; i++) { | |
localMax = Math.max(nums[i], localMax + nums[i]); | |
globalMax = Math.max(localMax, globalMax); | |
} | |
return globalMax; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment