Friday, August 19, 2022
HomeSoftware DevelopmentDecrease deletions such that sum of place of characters is at most...

Decrease deletions such that sum of place of characters is at most Okay


View Dialogue

Enhance Article

Save Article

Like Article

Given a string S consisting of decrease case letters and an integer Okay, the duty is to take away minimal variety of letters from the string, such that the sum of alphabetic ordering of the letters current within the string is at most Okay.

Examples :

Enter: S = “abca”, Okay = 2
Output: “aa”
Rationalization: Preliminary sum for the given string is 1 + 2 + 3 + 1 = 7 
(since positions of a, b, and c are 1, 2, and three respectively). 
If we take away b and c from the string “abca”, it turns into “aa”,  
having price 2 which is lower than or equal to the given Okay.

Enter: S = “geeksforgeeks”, Okay= 27
Output: “eefee”

 

Method: The issue may be simply solved by a grasping method. 

The principle statement is that first, we should take away the characters having most price earlier than eradicating the characters having lesser price. 

  • First create a variable (say totalCost), to retailer the entire price of the preliminary string S.
  • Then create a replica of string S (say temp) and kind it in reverse order of characters.
  • Traverse by way of temp and preserve storing the characters in a map (say del), until totalCost is bigger than Okay.
    • These characters saved within the map are mainly the characters to be deleted.
  • Lastly, traverse by way of the string S, delete the characters saved within the map del, and return the ultimate string.

Under is the implementation of the above method:

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

string findMaxSubstring(string S, int Okay)

{

    int n = S.dimension();

  

    

    

    int totalCost = 0;

    for (int i = 0; i < n; i++) {

        totalCost += (S[i] - 'a' + 1);

    }

  

    

    

    string temp(S);

  

    

    

    kind(temp.rbegin(), temp.rend());

    map<char, int> del;

  

    

    

    

    for (int i = 0; i < temp.size(); i++) {

        if (totalCost > Okay) {

            del[temp[i]]++;

            totalCost -= temp[i] - 'a' + 1;

        }

    }

  

    string ans;

  

    

    

    

    

    for (int i = 0; i < n; i++) {

        if (del[S[i]] > 0) {

            del[S[i]]--;

        }

        else {

            ans += S[i];

        }

    }

  

    

    return ans;

}

  

int most important()

{

    string S = "geeksforgeeks";

    int Okay = 27;

  

    

    string ans = findMaxSubstring(S, Okay);

    cout << ans;

    return 0;

}

Time Complexity: O(N * log(N)) the place N is the size of the string
Auxiliary House: O(N)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments