Tuesday, 26 Oct 2021

# Lexicographically largest string with sum of characters equal to N

Lexicographically largest string with sum of characters equal to NGiven a positive integer N, the task is to find the lexicographically largest string consisting of lower-case English alphabets such that the sum of the characters of the string equals N where ‘a’ = 1, ‘b’ = 2, ‘c’ = 3, ….. , and ‘z’ = 26.Examples:Input: N = 30Output: zdExplanation:The lexicographically largest string formed is “zd” whose sum of position of characters is (26 + 4) = 30(= N).Input: N = 14Output: nApproach: To make lexicographically the largest string, the idea is to print the character z, N/26 number of times and then the character at (N%26 + 1)th position in the English alphabets. Follow the steps below to solve the problem:Initialize a string, say ans, that stores the required lexicographically largest string.Iterate until N is at least 26 and perform the following steps:Add the character z to the string ans.Decrement the value of N by 26.Add the value of char(N + ‘a’) to the string ans.After completing the above steps, print the value of ans as the resultant string.Below is the implementation of the above approach:  #include using namespace std;  string getString(int N){        string ans = “”;          while (N >= 26) {                  ans += ‘z’;                  N -= 26;    }          ans += char(N + ‘a’ – 1);          return ans;}  int main(){    int N = 30;    cout