Skip to content

Commit

Permalink
https://leetcode.com/problems/maximum-subarray/
Browse files Browse the repository at this point in the history
  • Loading branch information
s50600822 committed Nov 5, 2023
1 parent 2e98b0e commit 49fa753
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
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;
}
}
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}));
}
}

0 comments on commit 49fa753

Please sign in to comment.