We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The idea being that you are either eating your cupcake last, or eating it first.
The ordering of the sort shouldn't matter.
The non-greedy interpretation is that
W[j]= W[j] + 2^(j-1) * C[j-1]
That's the
sum += 2**(j-1) * C[j-1] solution.
One can prove that
W[j] = W[j-1]+ 2^(j-1) * C[j-1]
by induction, but I needed to assume that C[j] > 0forall j, and that C[j] >= C[j-1] (that the list is sorted in ascending order)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Marc's Cakewalk
You are viewing a single comment's thread. Return to all comments →
I was wondering about the greedy vs non-greedy approach too.
I think that if you want to use the greedy solution, you can sort then:
W[j] = min(W[j-1] + 2^(j-1) * C[j-1], C[j-1] + W[j-1] * 2)
W(0) = 0
The idea being that you are either eating your cupcake last, or eating it first. The ordering of the sort shouldn't matter.
The non-greedy interpretation is that
W[j]= W[j] + 2^(j-1) * C[j-1]
That's thesum += 2**(j-1) * C[j-1]
solution.One can prove that
W[j] = W[j-1]+ 2^(j-1) * C[j-1]
by induction, but I needed to assume thatC[j] > 0
forall j, and thatC[j] >= C[j-1]
(that the list is sorted in ascending order)