Created
April 12, 2020 17:21
-
-
Save ozkansari/aba50224dde57f7e157a6a3f973d43a9 to your computer and use it in GitHub Desktop.
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3285/
This file contains 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 class MaxSubArray { | |
public static void main(String[] args) { | |
MaxSubArray problem = new MaxSubArray(); | |
int result1 = problem.calculate(new int[] { -2,1,-3,4,-1,2,1,-5,4 }); | |
System.out.println("Expected: 6, Result: " + result1); | |
} | |
public int calculate(int[] nums) { | |
int subSum = nums[0]; | |
int maxSum = subSum; | |
for(int i=1; i<nums.length; i++){ | |
// reset sub-sum if current num is greater than pre-sum | |
if(nums[i] > subSum+nums[i]) { | |
subSum = 0; | |
} | |
maxSum = Math.max(maxSum,subSum+nums[i]); | |
subSum += nums[i]; | |
} | |
return maxSum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very complex question