Lexicographically largest string with sum of characters equal to N
Given 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.
Input: N = 30
The lexicographically largest string formed is “zd” whose sum of position of characters is (26 + 4) = 30(= N).
Input: N = 14
Approach: 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:
Time Complexity: O(N)
Auxiliary Space: O(N)