From 49fa7539e1ee3d33b73217dbe68b373236b51473 Mon Sep 17 00:00:00 2001 From: s50600822 Date: Sun, 5 Nov 2023 14:12:14 +1100 Subject: [PATCH] https://leetcode.com/problems/maximum-subarray/ --- .../main/java/hoa/can/code/med/MaxSubArr.java | 21 +++++++++++++++++++ .../java/hoa/can/code/MaxSubArrSumTest.java | 19 +++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 interview_prep/algorithm/java/src/main/java/hoa/can/code/med/MaxSubArr.java create mode 100644 interview_prep/algorithm/java/src/test/java/hoa/can/code/MaxSubArrSumTest.java diff --git a/interview_prep/algorithm/java/src/main/java/hoa/can/code/med/MaxSubArr.java b/interview_prep/algorithm/java/src/main/java/hoa/can/code/med/MaxSubArr.java new file mode 100644 index 00000000..04309169 --- /dev/null +++ b/interview_prep/algorithm/java/src/main/java/hoa/can/code/med/MaxSubArr.java @@ -0,0 +1,21 @@ +package hoa.can.code.med; + +/** + * desc + */ +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; + } +} diff --git a/interview_prep/algorithm/java/src/test/java/hoa/can/code/MaxSubArrSumTest.java b/interview_prep/algorithm/java/src/test/java/hoa/can/code/MaxSubArrSumTest.java new file mode 100644 index 00000000..93fb02e9 --- /dev/null +++ b/interview_prep/algorithm/java/src/test/java/hoa/can/code/MaxSubArrSumTest.java @@ -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})); + } +}