-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
https://leetcode.com/problems/maximum-subarray/
- Loading branch information
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
interview_prep/algorithm/java/src/main/java/hoa/can/code/med/MaxSubArr.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package hoa.can.code.med; | ||
|
||
/** | ||
* <a href="https://leetcode.com/problems/maximum-subarray/">desc</a> | ||
*/ | ||
public class MaxSubArr { | ||
public int maxSubArray(int[] nums) { | ||
int maxSoFar = Integer.MIN_VALUE; | ||
int maxEndingAt = 0; | ||
for (int num : nums) { | ||
maxEndingAt = maxEndingAt + num; | ||
if (maxSoFar < maxEndingAt) { | ||
maxSoFar = maxEndingAt; | ||
} | ||
if (maxEndingAt < 0) { | ||
maxEndingAt = 0; | ||
} | ||
} | ||
return maxSoFar; | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
interview_prep/algorithm/java/src/test/java/hoa/can/code/MaxSubArrSumTest.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package hoa.can.code; | ||
|
||
import hoa.can.code.ez.LongestPalindrome; | ||
import hoa.can.code.med.MaxSubArr; | ||
import org.junit.jupiter.api.DisplayName; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
public class MaxSubArrSumTest { | ||
MaxSubArr tst = new MaxSubArr(); | ||
@Test | ||
@DisplayName("max sub arr sum") | ||
public void test(){ | ||
assertEquals(1, tst.maxSubArray(new int[]{1})); | ||
assertEquals(6, tst.maxSubArray(new int[]{-2,1,-3,4,-1,2,1,-5,4})); | ||
assertEquals(23, tst.maxSubArray(new int[]{5,4,-1,7,8})); | ||
} | ||
} |