(Hacker Rank) The Longest Common Subsequence - Solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static int sizeSeqA;
    public static int sizeSeqB;
    public static int[] seqA;
    public static int[] seqB;
    public static int[][] memo;
       
    public static int lcs(int indexA, int indexB) {
        if (indexA == sizeSeqA || indexB == sizeSeqB) {
            return 0;
        }   
       
        if (memo[indexA][indexB] != -1) {
            return memo[indexA][indexB];
        }
       
        int nextA = lcs(indexA+1, indexB);
        int nextB = lcs(indexA, indexB+1);
        int nextBoth = lcs(indexA+1, indexB+1) + ((seqA[indexA] == seqB[indexB]) ? 1 : 0);
       
        memo[indexA][indexB] = Math.max(nextA, Math.max(nextB, nextBoth));
        return memo[indexA][indexB];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        sizeSeqA = sc.nextInt();
        sizeSeqB = sc.nextInt();
        seqA = new int[sizeSeqA];
        seqB = new int[sizeSeqB];
        for (int i = 0; i < sizeSeqA; i++) {
            seqA[i] = sc.nextInt();
        }
        for (int i = 0; i < sizeSeqB; i++) {
            seqB[i] = sc.nextInt();
        }
       
        memo = new int[sizeSeqA+1][sizeSeqB+1];
        for (int i = 0; i < sizeSeqA+1; i++) {
            for (int j = 0; j < sizeSeqB+1; j++) {
                memo[i][j] = -1;
            }
        }
       
        lcs(0, 0);
       
        int row = 0;
        int col = 0;
        int value = memo[row][col];
        ArrayList<Integer> sequence = new ArrayList<>();
        while (value != -1 && value != 0) {
            if (memo[row+1][col] == value) {
                row++;
            } else if (memo[row][col+1] == value) {
                col++;
            } else {
                sequence.add(row);
                row++;
                col++;
            }
            value = memo[row][col];
        }
       
        for (int i = 0; i < sequence.size(); i++) {
            if (i == sequence.size()-1) {
                System.out.println(seqA[sequence.get(i)]);
                break;
            }
            System.out.print(seqA[sequence.get(i)] + " ");
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução