Greedy Algorithms8 sections · 316 units
Open in Course

Broken Calculator - Reverse Greedy

Halve or add

Work backwards: transform YY to XX. The reverse operations are halve (if even) or add 11. Greedy: if Y>XY > X and YY is even, halve it.

If YY is odd, add 11 (makes it even for halving).

If Y≤XY \leq X, just add X−YX - Y. Halving is powerful: it reduces YY quickly. Adding is cheap but slow. Prioritize halving when possible. Why this is optimal: halving reduces YY by a factor of 22, which is exponentially faster than adding 11.

If YY is odd, you must add 11 to make it even before halving. Once Y≤XY \leq X, halving would undershoot, so you switch to adding the difference.