Related Articles

# Minimum cost for constructing the subsequence of length K from given string S

• Last Updated : 21 Jul, 2021

Given a string S consisting of N lowercase English alphabets, and an integer K and, an array cost[] of size 26 denoting the cost of each lowercase English alphabet, the task is to find the minimum cost to construct a subsequence of length K from the characters of the string S.

Examples:

Input: S = “aabcbc”, K = 3, cost[] = {2, 1, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}
Output: 4
Explanation:
One way to construct a string of size K(= 3) is:
Form the string “abb” taking two ‘b’s with a cost of (2*1 = 2), and one ‘a’ with a cost of (1*2 = 2).
Therefore, the total cost to construct the string “abb” is (2 + 2 = 4), which is the minimum possible.

Input: S = “aaaca”, K = 1, cost[] = {2, 1, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}
Output: 2

Approach: The given problem can be solved by sorting the array cost[] in increasing order and include the first K characters having the minimum cost that are present in the given string S. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Custom comparator to sort according``// to the second element``bool` `comparator(pair<``char``, ``int``> p1,``                ``pair<``char``, ``int``> p2)``{``    ``return` `p1.second < p2.second;``}` `// Function to find the minimum cost``// to construct a subsequence of the``// length K``int` `minimumCost(string S, ``int` `N,``                ``int` `K, ``int` `cost[])``{``    ``// Stores the minimum cost``    ``int` `minCost = 0;` `    ``// Stores the pair of character``    ``// and the cost of that character``    ``vector > V;` `    ``// Stores the frequency of each``    ``// character``    ``unordered_map<``char``, ``int``> mp;` `    ``// Iterate in the range [0, N-1]``    ``for` `(``int` `i = 0; i < N; i++)``        ``mp[S[i]]++;` `    ``// Iterate in the range [0, 25]``    ``for` `(``int` `i = 0; i < 26; i++) {``        ``V.push_back({ ``char``(``'a'` `+ i), cost[i] });``    ``}` `    ``// Sort the vector of pairs V``    ``// wrt the second element``    ``sort(V.begin(), V.end(), comparator);` `    ``// Iterate in the range [0, 25]``    ``for` `(``int` `i = 0; i < 26; i++) {` `        ``// Stores the frequency of the``        ``// current char in the string``        ``int` `count = mp[``char``(``'a'` `+ i)];` `        ``// If count is less than``        ``// or equal to K``        ``if` `(count >= K) {` `            ``// Update the value of``            ``// minCost``            ``minCost += V[i].second * K;``            ``break``;``        ``}``        ``else` `if` `(count < K) {` `            ``// Update the value of``            ``// minCost``            ``minCost += V[i].second * count;` `            ``// Update the value``            ``// of K``            ``K = K - count;``        ``}``    ``}` `    ``// Print the value of minCost``    ``return` `minCost;``}` `// Driver Code``int` `main()``{``    ``string S = ``"aabcbc"``;``    ``int` `K = 3;``    ``int` `cost = { 2, 1, 3, 9, 9, 9, 9,``                     ``9, 9, 9, 9, 9, 9, 9,``                     ``9, 9, 9, 9, 9, 9, 9,``                     ``9, 9, 9, 9, 9 };``    ``int` `N = S.length();``    ``cout << minimumCost(S, N, K, cost);` `    ``return` `0;``}`

## Python3

 `# Python3 program for the above approach` `# Function to find the minimum cost``# to construct a subsequence of the``# length K``def` `minimumCost(S, N, K, cost):``    ` `    ``# Stores the minimum cost``    ``minCost ``=` `0` `    ``# Stores the pair of character``    ``# and the cost of that character``    ``V ``=` `[]` `    ``# Stores the frequency of each``    ``# character``    ``mp ``=` `{}` `    ``# Iterate in the range [0, N-1]``    ``for` `i ``in` `range``(N):``        ``if` `(S[i] ``in` `mp):``            ``mp[S[i]] ``+``=` `1``        ``else``:``            ``mp[S[i]] ``=` `1` `    ``# Iterate in the range [0, 25]``    ``for` `i ``in` `range``(``26``):``        ``V.append([``chr``(``ord``(``'a'``) ``+` `i), cost[i]])` `    ``# Sort the array of pairs V``    ``# with the second element``    ``while` `(``1``):``        ``flag ``=` `0` `        ``for` `i ``in` `range``(``len``(V) ``-` `1``):``            ``if` `(V[i][``1``] > V[i ``+` `1``][``1``]):``                ``temp ``=` `V[i]``                ``V[i] ``=` `V[i ``+` `1``]``                ``V[i ``+` `1``] ``=` `temp``                ``flag ``=` `1` `        ``if` `(flag ``=``=` `0``):``            ``break` `    ``# Iterate in the range [0, 25]``    ``for` `i ``in` `range``(``26``):` `        ``# Stores the frequency of the``        ``# current char in the string``        ``count ``=` `mp[``chr``(``ord``(``'a'``) ``+` `i)]` `        ``# If count is less than``        ``# or equal to K``        ``if` `(count >``=` `K):` `            ``# Update the value of``            ``# minCost``            ``minCost ``+``=` `V[i][``1``] ``*` `K``            ``break` `        ``elif` `(count < K):` `            ``# Update the value of``            ``# minCost``            ``minCost ``+``=` `V[i][``1``] ``*` `count` `            ``# Update the value``            ``# of K``            ``K ``=` `K ``-` `count` `    ``# Print the value of minCost``    ``return` `minCost` `# Driver Code``S ``=` `"aabcbc"``K ``=` `3``cost ``=` `[ ``2``, ``1``, ``3``, ``9``, ``9``, ``9``, ``9``,``         ``9``, ``9``, ``9``, ``9``, ``9``, ``9``, ``9``,``         ``9``, ``9``, ``9``, ``9``, ``9``, ``9``, ``9``,``         ``9``, ``9``, ``9``, ``9``, ``9` `]``N ``=` `len``(S)` `print``(minimumCost(S, N, K, cost))` `# This code is contributed by _saurabh_jaiswal`

## Javascript

 ``
Output:
`4`

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up