Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Bag of Tokens

Play optimally

You have tokens with values and start with power PP and score 00.

You can play token ii face-up (lose tokens[i]tokens[i] power, gain 11 score) if you have enough power. Or play face-down (gain tokens[i]tokens[i] power, lose 11 score) if score >0> 0. Maximize final score.

Think about when to spend power and when to cash in score for power. Tricky: playing face-down gives you power but costs score.

You only do this when you cannot afford any face-up plays. The two-pointer setup ensures you always have access to both the smallest (cheapest to play face-up) and largest (best power gain face-down) tokens.