I am trying to find a sub-array in array {-2, -3, 4, -1, -2, 1, 5, -3} where the sum of the values is the maximum and print this array out. The result should be [4, -1, -2, 1, 5]. But in my case the result is [-2, 1, 5], that is wrong 🤔
static String maxSubArraySum(int[] a, int size)
{
int max_so_far = a[0];
int curr_max = a[0];
for (int i = 1; i < size; i++)
{
curr_max = Math.max(a[i], curr_max+a[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
int [] res = Arrays.copyOfRange(a, curr_max, max_so_far);
return Arrays.toString(res);
}
public static void main(String[] args)
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = a.length;
String arr = maxSubArraySum(a, n);
System.out.println("Result is " + arr);
}