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

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:4Explanation:

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:

- Initialize a vector of pair of char and int say,
**V**to store the character - Also, initialize a map say
**mp**with key as character and value as integers to store the frequency of each character of the string**S**. - Traverse the given string using the variable
**i**and in each iteration increment the value of**mp[S[i]]**. - Iterate over the range
**[0, 25]**using the variable**i**and in each iteration append the pair**{char(‘a’ + i), cost[i]}**to the vector of pairs**V**. - Sort the vector of pairs V[]
- Now, initialize a variable, say
**minCost**as**0**to store the minimum cost of a subsequence of length**K**. - Iterate over the range
**[0, 25]**using the variable**i**and perform the following steps:- Initialize a variable say,
**count**as**mp[‘a’ + i]**. - If the value of
**count**is less than**K**, then add the value of**count*V[i].second**to the value of**minCost**and update the value of**K**to**K – count**. - Otherwise, add
**K*V[i].second**to the value of**minCost**and break out of the loop.

- Initialize a variable say,
- After completing the above steps, print the value of
**minCost**as the result.

Below is the implementation of the above approach:

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `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<pair<` `char` `, ` `int` `> > 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[26] = { 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

`<script>` `// Javascript program for the above approach` `// Function to find the minimum cost` `// to construct a subsequence of the` `// length K` `function` `minimumCost(S, N, K, cost) {` ` ` `// Stores the minimum cost` ` ` `let minCost = 0;` ` ` `// Stores the pair of character` ` ` `// and the cost of that character` ` ` `let V = [];` ` ` `// Stores the frequency of each` ` ` `// character` ` ` `let mp = ` `new` `Map();` ` ` `// Iterate in the range [0, N-1]` ` ` `for` `(let i = 0; i < N; i++) {` ` ` `if` `(mp.has(S[i])) {` ` ` `mp.set(S[i], mp.get(S[i]) + 1)` ` ` `} ` `else` `{` ` ` `mp.set(S[i], 1)` ` ` `}` ` ` `}` ` ` `// Iterate in the range [0, 25]` ` ` `for` `(let i = 0; i < 26; i++) {` ` ` `V.push([String.fromCharCode(` `'a'` `.charCodeAt(0) + i), cost[i]]);` ` ` `}` ` ` `// Sort the array of pairs V` ` ` `// with the second element` ` ` `while` `(1) {` ` ` `let flag = 0;` ` ` `for` `(let i = 0; i < V.length - 1; i++) {` ` ` `if` `(V[i][1] > V[i + 1][1]) {` ` ` `let 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` `(let i = 0; i < 26; i++) {` ` ` `// Stores the frequency of the` ` ` `// current char in the string` ` ` `let count = mp.get(String.fromCharCode(` `'a'` `.charCodeAt(0) + i));` ` ` `// If count is less than` ` ` `// or equal to K` ` ` `if` `(count >= K) {` ` ` `// Update the value of` ` ` `// minCost` ` ` `minCost += V[i][1] * K;` ` ` `break` `;` ` ` `}` ` ` `else` `if` `(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` `let S = ` `"aabcbc"` `;` `let K = 3;` `let 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];` `let N = S.length;` `document.write(minimumCost(S, N, K, cost));` `// This code is contributed by gfgking.` `</script>` |

**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**.