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; | |
} | |
} |
--
Hiç yorum yok:
Yorum Gönder