Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Broken Calculator

Work backwards

Given start value XX and target YY, you can double XX or subtract 11. Find minimum operations to reach YY. For X=2X=2, Y=3Y=3: double to 44, subtract to 33. Answer is 22. Going forward is hard because doubling can overshoot.

Think about working backwards from YY to XX. Tricky: working forward with doubling can overshoot YY, making it hard to determine the optimal path. Working backward with halving and adding is deterministic: if YY is even, halving is always better than adding (halving reduces by half, adding by 11).

This guides the greedy choice.