A string is said to contain a value that is known as its beauty.
You are given pairings where the pairing is . Here, and are lowercase English letters and is a positive integer.
There exists a string of length . For the pairing, let the number of indices such that and be . The beauty of is the sum of for each .
You are given a string of length 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 .
Example:
Input:6 abdbca 5 a b 2 a b 3 b c 10 b a 6 a c 8Output: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