0

I would like to find the maximal subsequence S(h,k) in an array of integer. I already have the code (in Java) to find the maximum value and it works fine, but how can I get the two indexes h and k from the following?

int []a = {-2, 1, -3, 4, -1, 2, 1, -5, 4 };
int max_so_far = 0, max_ending_here = 0;
for(int i=0; i<a.length; i++) {
    max_ending_here = Math.max(0, max_ending_here + a[i]);
    max_so_far = Math.max(max_so_far, max_ending_here);
}
System.out.println("The maximal sum of subsequence is = "+max_so_far)";
Gio Bact
  • 541
  • 1
  • 7
  • 23

2 Answers2

0

You can get the subsequence itself by storing the last index at which you improved max_so_far, and "unraveling" the sequence from the back:

int []a = {-2, 1, -3, 4, -1, 2, 1, -5, 4 };
int max_so_far = 0, max_ending_here = 0, index_max = 0;
for(int i=0; i<a.length; i++) {
    max_ending_here = Math.max(0, max_ending_here + a[i]);
    if (max_so_far < max_ending_here) {
        max_so_far = max_ending_here;
        index_max = i;
    }
}
System.out.print("The maximal sum of subsequence is = "+max_so_far);
int j = index_max;
while (j >= 0 && max_so_far > 0) {
    max_so_far -= a[j--];
}
System.out.println(", from = "+(j+1)+" to "+index_max+", inclusive");

Demo.

Note: Unraveling from the back using a marker is a common theme in dynamic programming algorithms. In your simple case index_max plays the role of a special marker, from which you look backward for the index that runs max_so_far into zero.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Thank to Shreyas Sarvothama and dasblinkenlight for their answers. I found a good solution this code written by Utsav Chokshi on the geeksforgeeks.org website.

The solution is:

int []a = {-2, 1, -3, 4, -1, 2, 1, -5, 4 };
int max_so_far = a[0], max_ending_here = a[0];
int curStartIndex = 0;
int maxStartIndex = 0;
int maxEndIndex = 0;

for(int i=1; i<a.length; i++) {
        max_ending_here = Math.max(a[i], max_ending_here + a[i]);
        if(max_ending_here > max_so_far){
             max_so_far = max_ending_here;
             maxStartIndex = curStartIndex;
             maxEndIndex = i;
        }
        if(max_ending_here < 0){
            curStartIndex = i+1;
        }
}
Gio Bact
  • 541
  • 1
  • 7
  • 23