I have an array of integers and I want to find the maximum subsequence sum (MSS). I'm trying to solve this problem recursively - using divide and conquer.
The idea is to split the array into half, recurse on the two halves, and then find the maximum sum of the left and right halves of the array, and then compare them with the values I got from recursion.
I know that there are other ways to solve the problem. However, I want to figure out the bug in my code before I look at the other solutions. Right now, with my input, I'm getting the MSS as 12, when it should be 8 (2, 5, -5, 5, 1)
import java.lang.Math;
public class Solution {
public static void main(String[] args){
int[] arr = new int[7];
arr[0] = 1;
arr[1] = -3;
arr[2] = 2;
arr[3] = 5;
arr[4] = -5;
arr[5] = 5;
arr[6] = 1;
System.out.println(helper(arr, 0, arr.length - 1));
}
public static int helper(int[] arr, int low, int high) {
if (low >= high) {
return Math.max(arr[low], 0);
}
int mid = low + (high - low) / 2;
int L = helper(arr, low, mid);
int R = helper(arr, mid + 1, high);
int sum = 0;
int leftSum = 0;
for (int i = mid - 1; i >= 0; i--) {
sum = sum + arr[i];
leftSum = Math.max(leftSum, sum);
}
sum = 0;
int rightSum = 0;
for (int i = high; i >= mid; i--) {
sum = sum + arr[i];
rightSum = Math.max(rightSum, sum);
}
return Math.max(L, Math.max(R, leftSum + rightSum));
}
}
Where exactly am I going wrong?
Edit: I'm trying to find the maximum contiguous sum