Last active
July 15, 2019 02:42
-
-
Save WennderSantos/2256be4706a4f3cd6121ab322116a918 to your computer and use it in GitHub Desktop.
Get the smallest string given a weight (all chars have a weight) - using array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Time: O(n) where n is weight | |
//Memory: O(1) weights array helper with length . of 26 | |
//In this solution, I am searching in the array of weights from biggest to smallet | |
//comparing values with weight searched. | |
//When find a value in the array that fits the weight being searched | |
//use array index to calculate a char ascii value which represent a | |
//character wight in the result. | |
public static string smallestString2(BigInteger weight) | |
{ | |
var weigths = new BigInteger[26]; | |
var startAscii = 65; | |
weigths[0] = 1; | |
for (int i = 1; i < 26; i++) | |
{ | |
var letterWeight = (i + 1) * weigths[i-1] + weigths[i - 1]; | |
weigths[i] = letterWeight; | |
} | |
var sb = new StringBuilder(); | |
var j = 25; | |
while (j >= 0) | |
{ | |
if (weigths[j] <= weight) | |
{ | |
var count = 1; | |
while (weigths[j] * count <= weight) | |
{ | |
sb.Insert(0, Convert.ToChar(startAscii + j)); | |
count++; | |
} | |
weight -= weigths[j] * (count - 1); | |
} | |
j--; | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment