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); + } +}