Designer Pdf Viewer

See the original problem on HackerRank.

Solutions

We just calculate the resulting area as the product between the number of chars and the maximum height.

Here is a Python implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def get_rect_height(word, height_arr):
    height = 0
    for c in word:
        height = max(height, height_arr[ ord(c) - ord("a") ])
        #ord(character) gives the ascii value
    return height

heights = [int(x) for x in raw_input().split()]	#scan heights
word = raw_input()

print len(w) * get_rect_height(w, heights)

Here is a C++ implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
array<int, 26> h;
copy_n(istream_iterator<int>(cin), 26, begin(h));        
string s; 
cin >> s;

int maxHeight = 0;

for (int j = 0; j < s.length(); j ++) 
{
    maxHeight = max(maxHeight, h[s[j] - 'a']);
}
    
cout << (maxHeight * s.size());

A variant using no raw loops:

1
2
3
4
5
6
7
8
array<int, 26> h;
copy_n(istream_iterator<int>(cin), 26, begin(h));
std::vector<int> v;
std::transform(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(v), [&](char c){
  return h[c - 'a'];
});
auto maxHeight = *max_element(begin(v), end(v));
cout << (v.size() * maxHeight);

A variant that solves the problem while reading the input and using the reduce idiom:

1
2
3
4
5
6
7
array<int, 26> h;
copy_n(istream_iterator<int>(cin), 26, begin(h));
auto res = 
    accumulate(istream_iterator<char>(cin), istream_iterator<char>(), pair<int, int>{}, [&](auto curr, char c){
        return make_pair(curr.first + 1, max(curr.second, h[c-'a']));
});
cout << (res.first*res.second);
We've worked on this challenge in these gyms: modena  padua 
comments powered by Disqus