Given a string str and an integer K, the task is to find the longest string that can be made by deleting letters from the given string such that the sum of the characters of the remaining string is at most K.
Note: The value of the string is calculated as the sum of the value of characters (a value is 1, b value is 2…., z value is 26).
Examples:
Input: str = “geeksforgeeks”, K = 15
Output: eee
Explanation: After deleting the characters string gets reduced to eee whose value is 5 + 5 + 5 = 15 which is less than or equal to K i.e. 15Input: str = “abca”, K = 6
Output: aba
Explanation: Initial value of str 1 + 2 + 3 + 1 = 7, after deleting the letter c, the string gets reduced to aba whose value is 1+2+1 = 4 which is less than K i.e. 6.
Approach: The problem can be solved using Greedy approach based on the following idea:
We must delete letters with the highest value first. So, we sort the string str in decreasing order and will be deleting letters from the starting of string str as long as the initial value of string str is greater than the given value K.
Follow the steps mentioned below to implement the idea:
- Calculate the initial value of the given string.
- Sort the string str in decreasing order
- Start removing the value of the current letter from the initial value as long as the initial value is greater than K.
- Store the removed characters in the map
- Iterate through the given string once again and
- If the current letter does not exist in the map take it into the resultant string
- Else decrease the frequency of the letter
- Return the resultant string
Below is the implementation of the above approach:
C++
|
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Related Articles:
Stay connected with us on social media platform for instant update click here to join our Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here