Generate longest String with character sum at most K by deleting letters
Last Updated :
21 Feb, 2023
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. 15
Input: 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++
#include <bits/stdc++.h>
using namespace std;
string minimise_str(string str, int K)
{
int initial_value = 0;
for ( int i = 0; i < str.length(); i++) {
initial_value += (str[i] - 'a' ) + 1;
}
string temp = str;
sort(str.begin(), str.end());
reverse(str.begin(), str.end());
unordered_map< char , int > mpp;
int i = 0;
while (initial_value > K) {
initial_value -= (str[i] - 'a' ) + 1;
mpp[str[i]]++;
i++;
}
string ans = "" ;
for ( int i = 0; i < temp.size(); i++) {
if (mpp[temp[i]] > 0) {
mpp[temp[i]]--;
}
else {
ans += temp[i];
}
}
return ans;
}
int main()
{
string str = "geeksforgeeks" ;
int K = 15;
cout << minimise_str(str, K);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String minimiseStr(String str, int K)
{
int initialValue = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
initialValue += (str.charAt(i) - 'a' ) + 1 ;
}
String temp = str;
char [] chars = str.toCharArray();
Arrays.sort(chars);
str = new StringBuilder( new String(chars))
.reverse()
.toString();
Map<Character, Integer> mpp = new HashMap<>();
int i = 0 ;
while (initialValue > K) {
initialValue -= (str.charAt(i) - 'a' ) + 1 ;
mpp.put(str.charAt(i),
mpp.getOrDefault(str.charAt(i), 0 ) + 1 );
i++;
}
StringBuilder ans = new StringBuilder();
for ( int j = 0 ; j < temp.length(); j++) {
if (mpp.containsKey(temp.charAt(j))
&& mpp.get(temp.charAt(j)) > 0 ) {
int freq = mpp.get(temp.charAt(j));
mpp.put(temp.charAt(j), freq - 1 );
}
else {
ans.append(temp.charAt(j));
}
}
return ans.toString();
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int K = 15 ;
System.out.println(minimiseStr(str, K));
}
}
|
Python3
import collections
def minimise_str( str , K):
initial_value = 0
for i in range ( len ( str )):
initial_value + = ( ord ( str [i]) - ord ( 'a' ) + 1 )
temp = str
str = ''.join( sorted ( str , reverse = True ))
mpp = collections.defaultdict( int )
i = 0
while initial_value > K:
initial_value - = ( ord ( str [i]) - ord ( 'a' ) + 1 )
mpp[ str [i]] + = 1
i + = 1
ans = ""
for i in range ( len (temp)):
if mpp[temp[i]] > 0 :
mpp[temp[i]] - = 1
else :
ans + = temp[i]
return ans
str = "geeksforgeeks"
K = 15
print (minimise_str( str , K))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static string MinimiseString( string str, int K)
{
int initial_value = 0;
foreach ( char c in str)
{
initial_value += (c - 'a' ) + 1;
}
string temp = str;
char [] arr = str.ToCharArray();
Array.Sort(arr);
Array.Reverse(arr);
str = new string (arr);
Dictionary< char , int > mpp = new Dictionary< char , int >();
int i = 0;
while (initial_value > K)
{
initial_value -= (str[i] - 'a' ) + 1;
if (mpp.ContainsKey(str[i]))
{
mpp[str[i]]++;
}
else
{
mpp[str[i]] = 1;
}
i++;
}
string ans = "" ;
foreach ( char c in temp)
{
if (mpp.ContainsKey(c) && mpp > 0)
{
mpp--;
}
else
{
ans += c;
}
}
return ans;
}
static void Main( string [] args)
{
string str = "geeksforgeeks" ;
int K = 15;
Console.WriteLine(MinimiseString(str, K));
}
}
|
Javascript
function minimiseStr(str, K) {
let initialValue = 0;
for (let i = 0; i < str.length; i++) {
initialValue += (str.charCodeAt(i) - 'a' .charCodeAt(0)) + 1;
}
let temp = str;
str = str.split( '' ).sort().reverse().join( '' );
let mpp = {};
let i = 0;
while (initialValue > K) {
initialValue -= (str.charCodeAt(i) - 'a' .charCodeAt(0)) + 1;
if (mpp[str[i]]) {
mpp[str[i]]++;
} else {
mpp[str[i]] = 1;
}
i++;
}
let ans = '' ;
for (let i = 0; i < temp.length; i++) {
if (mpp[temp[i]] > 0) {
mpp[temp[i]]--;
}
else {
ans += temp[i];
}
}
return ans;
}
let str = 'geeksforgeeks' ;
let K = 15;
document.write(minimiseStr(str, K));
|
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Related Articles:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...