Maximum beauty subsequences

A string is said to contain a value that is known as its beauty.

You are given M pairings where the ith pairing is {(ai,bi):ki}. Here, ai and bi are lowercase English letters and ki is a positive integer.

There exists a string S of length L. For the ith pairing, let the number of indices j[1,L1] such that Sj=ai and Sj+1=bi be counti. The beauty of S is the sum of countiki for each i[1,M].

You are given a string A of length N consisting of lowercase English letters. A string can be formed from a subsequence of a string by concatenating the characters of the subsequence in order of occurrence. You are required to find the maximum beauty that can be obtained by selecting any strings that can be formed by a subsequence of A

Example:

Input:
6 abdbca 5 a b 2 a b 3 b c 10 b a 6 a c 8
Output:
15

Approach

Java

import java.util.Arrays;

public class MaxBeautySubseq {

    public static void main(String args[]) {
        long[][] pairings = new long[26][26];
        int n = 6;
        String s = "abdbca";

        int m = 5;
        char arr[][] = { { 'a''b'2 }, { 'a''b'3 }, { 'b''c'10 }, { 'b''a'6 }, { 'a''c'8 } };
        for (int i = 0; i < m; i++) {
            int a = arr[i][0] - 'a';
            int b = arr[i][1] - 'a';
            int k = arr[i][2];
            pairings[a][b] += k;
        }

        long maxBeauty = 0;
        long[] beauty = new long[n];
        int[] indices = new int[26];

        Arrays.fill(indices, -1);
        indices[s.charAt(0) - 'a'] = 0;
        for (int i = 1; i < n; i++) {
            int b = s.charAt(i) - 'a';
            for (int a = 0; a < 26; a++) {
                if (pairings[a][b] > 0 && indices[a] >= 0) {
                    long curBeauty = beauty[indices[a]] + pairings[a][b];
                    maxBeauty = Math.max(maxBeauty, curBeauty);
                }
            }
            beauty[i] = maxBeauty;
            indices[b] = i;
        }
        System.out.print(maxBeauty);
    }

}


No comments:

Post a Comment