From 2ac4fd401ba199ecd4ae8d7fe97e6205fb19c0bd Mon Sep 17 00:00:00 2001 From: Leonid Date: Tue, 29 Apr 2025 14:19:17 +0300 Subject: [PATCH] =?UTF-8?q?Solved=20Maximum=20Subarray=20Sum=20(Kadane?= =?UTF-8?q?=E2=80=99s=20Algorithm)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/#naive-approach-by-iterating-over-all-subarrays-on-2-time-and-o1-space --- .../algos/codewars/MaximumSubarraySum.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/com/algos/codewars/MaximumSubarraySum.java diff --git a/src/main/java/com/algos/codewars/MaximumSubarraySum.java b/src/main/java/com/algos/codewars/MaximumSubarraySum.java new file mode 100644 index 0000000..ba33aba --- /dev/null +++ b/src/main/java/com/algos/codewars/MaximumSubarraySum.java @@ -0,0 +1,43 @@ +package com.algos.codewars; +//The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array +// or list of integers: +// +// Max.sequence(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}); +//// should be 6: {4, -1, 2, 1} +// +// Easy case is when the list is made up of only positive numbers and the maximum sum is the sum +// of the whole array. If the list is made up of only negative numbers, return 0 instead. +// +// Empty list is considered to have zero greatest sum. Note that the empty list or array is also +// a valid sublist/subarray. + +public class MaximumSubarraySum { + + public static void main(String[] args) { + int [] testArray = new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}; +// int[] testArray = new int[]{2, 3, -8, 7, -1, 2, 3}; + System.out.println(sequence(testArray)); + } + + public static int sequence(int[] arr) { + + if (arr.length == 0) { + return 0; + } + + int maxEnding = arr[0]; + int result = arr[0]; + + for (int i = 1; i < arr.length; i++) { +// if (maxEnding < 0) { +// maxEnding = arr[i]; +// } else { +// maxEnding + arr[i]; +// } + maxEnding = Math.max(arr[i], maxEnding + arr[i]); + result = Math.max(result, maxEnding); + } + + return Math.max(result, 0); + } +}