KatInterview

Best Final Score from Affine Card Purchases Under a Budget

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingsubset-searchpermutationsexchange-argument

Last updated

Choose a budget-limited subset of cards and an order to maximize a score updated by an affine rule, testing subset and ordering search and exchange-argument reasoning.

Card Combo Scoring

You begin with a running score of 0. You are given a collection of cards, where card i is a pair (m_i, c_i): a multiplier m_i and a price c_i.

Buying card i while your current score is s changes the score to:

s' = (s + 1) * m_i - c_i

You may buy any subset of the cards, including none, and you choose the order in which you buy them. Each card can be bought at most once. The prices of all cards you buy must add up to at most budget.

Return the largest final score you can reach.

Rules and clarifications

  • The price total depends only on which cards you pick, not on the order. The final score depends on both the picks and the order.
  • Buying nothing is allowed and leaves the score at 0. The answer is therefore never negative.
  • Cards with price 0 are always affordable and can be combined with other cards. A cheap card is worth buying whenever it helps the final result, even if the "main" card could be bought on its own.
  • Intermediate scores may be negative. A negative score in the middle of a sequence does not make the sequence invalid.
  • Every legal plan is a subset whose total price is at most budget, together with any ordering of that subset. Return the maximum over all such plans.

Input

  • cards: a list of [m, c] pairs of integers.
  • budget: an integer, the maximum total price you may spend.

Output

A single integer: the maximum achievable final score (at least 0).

Constraints

  • 0 <= len(cards) <= 8 (small enough that exploring all plans is feasible)
  • m_i is an integer
  • c_i >= 0, an integer
  • budget >= 0, an integer

Examples

Example 1

Input: best_final_score([[2, 1], [3, 2]], 3)

Output: 4

Example 2

Input: best_final_score([[1, 0], [10, 5]], 5)

Output: 15

Hints

Hint 1

The total price depends only on which cards you choose, so you can check the budget before worrying about order.

Hint 2

Each purchase is an affine function of the current score, and such functions generally do not commute, so the order matters. With a small number of cards you can try every order of every affordable subset.

Hint 3

Start your best answer at 0 (buying nothing), do not discard sequences whose intermediate score is negative, and remember that a free card may still be worth adding to a plan.