I’ve solved quite a few puzzles on HackerRank, but this one had me stumped. The actual algorithm didn’t seem too hard, although there is a bit of a trick to it. The problem I had was extending the solution afterwards to handle large numbers. Usually, it’s enough to use ‘long long’ throughout, but it still wasn’t passing all the test cases.
In the end, I narrowed down the problem to the following code:
long long maximiseScore( int N ) { std::vector<long long> health( N, 0 ); for ( size_t i = 0; i < N; ++i ) std::cin >> health[i]; long long sum = std::accumulate( health.begin(), health.end(), 0 ); // ... }
In case you didn’t spot it, the bug is that std::accumulate has inferred the type of the init parameter from 0 (zero), which is an int. So the sum is calculated as an int, then assigned into our long long variable. The solution is to cast the init to a long long (either using ‘LL’ or static_cast).
long long sum = std::accumulate( health.begin(), health.end(), 0LL );