VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-to-make-a-string-free-of-a-subsequence/

⇱ Minimum cost to make a string free of a subsequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum cost to make a string free of a subsequence

Last Updated : 15 Dec, 2022

Given string str consisting of lowercase English alphabets and an array of positive integer arr[] both of the same length. The task is to remove some characters from the given string such that no sub-sequence in the string forms the string "code". Cost of removing a character str[i] is arr[i]. Find the minimum cost to achieve the target.


Examples: 

Input: str = "code", arr[] = {3, 2, 1, 3} 
Output:
Remove 'd' which costs the minimum.
Input: str = "ccooddde", arr[] = {3, 2, 1, 3, 3, 5, 1, 6} 
Output:
Remove both the 'o' which cost 1 + 3 = 4 

Approach: If any sub-sequence with "code" is possible, then the removal of a single character is required. Cost for the removal of each character is given in arr[]. So, traverse the string and for each character which is either c, o, d or e calculate the cost of their removal. And finally, the minimum among the cost of removal of all characters is required minimum cost.
Below is the implementation of the above approach: 


Output: 
2

 

Time Complexity: O(n), where n is the size of the given array and string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Comment