HackerRank: Designer PDF Viewer

[Get the problem here]

screen-shot-2017-03-06-at-2-40-21-am

Andddd… I’m sure there’s a better way to solve this problem too but the solution I got:

screen-shot-2017-03-06-at-2-43-23-am

I think another solution would be to map the vector h to another array, perhaps vector h_word that contains a map of each character in the string word; for example if

h = ( 1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)

and the given string was abc then

h -> h_word = ( 1, 3, 1)

the intermediate step vector<int> h_temp would be to change all the characters in the string to the unicode value and then subtract the unicode value of ‘a’ from all the characters in h_temp. Eventually h_temp would contain the position of all the letters of the string in the alphabet relative to ‘a’. Then you can use an embedded for-loop to map each character in h_temp to a height in h and put it into h_word. To find the maximum height you would need a findMax function, like:


int findMax(vector<long int> arr){
long int max;

max = arr[0];

for (int i = 0; i < arr.size(); i++) {
if (max < arr[i]) {
max = arr[i];
}
}

return max;
}

The logic behind the solution I wrote is very similar but without the mapping and generation of another vector array. The function getHeightOf requires the array of the heights and the string and each character in the string is converted into a position in the array within the for-loop and the maximum height is ‘saved’ for that iteration and eventually returned as the for-loop completes.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s