I'm attempting to write a maximum subsequence product program that is based off of the recursive solution to the maximum subsequence sum program (that is, it will follow the same format).
It works so far on all cases except those where the result should be '0,' to indicate that there are no products within the sequence that are positive. For my five sequences below, it works on all but the last one:
sequence1 = new int[]{-2, 5, 4, 4};
sequence2 = new int[]{6, 5, 0, -3, -5, -3, 7};
sequence3 = new int[]{0, -1, 1, 5, 0, -3, -4};
sequence4 = new int[]{0, 3, 3};
sequence5 = new int[]{0, -3, 3};
And here is the recursive method, where a is the sequence, p1 is a[0] initially and p2 is a[last index]:
public static int msp3(int[] a, int p1, int p2) {
if (p1 == p2) {
if (a[p1] != 0) {
maxprod = a[p1];
} else {
maxprod = 0;
}
} else {
int m = (p1 + p2) / 2;
int L = msp3(a, p1, m);
int R = msp3(a, m + 1, p2);
int prodlt = 1, prodrt = 1, PL = 0, PR = 0;
int checkForSplit = 0;
for (int i = m; i >= p1; i--) {
if (a[i] != 0) {
prodlt = prodlt * a[i];
if (prodlt > PL) {
PL = prodlt;
}
} else {
if (i == m) {
prodlt = 1;
checkForSplit = 1;
}
}
}
for (int i = m + 1; i <= p2; i++) {
if (a[i] != 0) {
prodrt = prodrt * a[i];
if (prodrt > PR) {
PR = prodrt;
}
} else {
if (i == m + 1) {
prodrt = 1;
checkForSplit = 1;
}
}
}
if (checkForSplit == 0) {
maxprod = max3(L, R, PL * PR);
} else {
maxprod = max3(L, R, PL);
maxprod = max(maxprod, PR);
}
}
return maxprod;
}
A note about 'checkForSplit,' the value is 0 unless a[i] == 0, and we are checking the leftmost or rightmost index in the current subsequence, in which case it is set to 1. This triggers a different calculation of 'max3' where PL is not multiplied by PR, the logic being that if either PL or PR is a 0, it is possible that the other of the two is not, in which case they should not be multiplied.
As I said, this algorithm works for all but the 5th sequence.
Any ideas?