I've implemented a DP algorithm that finds the longest common subsequence in three arrays. The problem though, is that my algorithm doesn't work when the arrays are of different lengths, and I have no idea why. From what I can tell, my algorithm is correct, so I think it's something to do with the Java implementation. Here is my Java code:
static int[] lcsOf3(int[] X, int[] Y, int[] Z, int xLength, int yLength, int zLength) {
int[][][] S = new int[xLength + 1][yLength + 1][zLength + 1];
for (int i = 0; i <= xLength; i++) {
for (int j = 0; j <= yLength; j++) {
for (int k = 0; k <= zLength; k++) {
if (i == 0 || j == 0 || k == 0) {
S[i][j][k] = 0;
} else if (X[i - 1] == Y[j - 1] && X[i - 1] == Z[k - 1]) {
S[i][j][k]= S[i - 1][j - 1][k - 1] + 1;
} else {
S[i][j][k] = Math.max(Math.max(S[i - 1][j][k], S[i][j - 1][k]), S[i][j][k - 1]);
}
}
}
}
System.out.println(S[xLength][yLength][zLength]);
}