Apparently it is by a backwards derivation solution. Say energy at h[i] is e, the next energy at h[i+1] is 2*e - h[i+1] => e', so backwards, e = ceil((e' + h[i + 1])/2). We assume energy is 0 at h[n-1]:
#include <string> #include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <queue> #include <unordered_map> #include <functional> using namespace std; int main() { int n; cin >> n; vector<int> hs(n); for (int i = 0; i < n; i++) cin >> hs[i]; long long ret = ceil(hs[n - 1] / 2.0); for (int i = n - 2; i >= 0; i--) ret = ceil((hs[i] + ret) / 2.0); cout << ret << endl; return 0; }