Best Final Score from Affine Card Purchases Under a Budget
Dynamic ProgrammingAuto-graded · 22 test casesLast 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
0are 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_iis an integerc_i >= 0, an integerbudget >= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each card acts as a function of the current score: f(s) = m * s + (m - c). Choosing a plan means choosing two things:
- Which cards to buy. The total price is the sum of the chosen prices, regardless of order. This is the only thing the budget constrains.
- In what order to buy them. Affine functions do not commute, so different orders give different final scores.
Because the number of cards is small, we can search exhaustively:
- Start with
best = 0, representing buying nothing. - Enumerate every non-empty subset with a bitmask.
- Skip any subset whose total price exceeds the budget.
- For each remaining subset, try every permutation, simulate the update rule from score
0, and keep the maximum.
Why it is correct
The set of legal plans is exactly "a subset within budget, in any order". The search visits every such plan and evaluates it with the exact update rule. It never prunes negative intermediate scores, so plans that dip below zero and recover later are still considered. Starting best at 0 covers the empty plan. Because every legal plan is evaluated, the maximum is correct without any assumption about the multipliers (zero, below one, or negative are all handled).
For the second sample, [[1,0],[10,5]] with budget 5: buying the free card (1,0) first gives score 1, then (10,5) gives (1+1)*10 - 5 = 15. That beats buying only the second card (5).
Complexity
- Time: the sum over subset sizes
kofC(n,k) * k! * k, which isO(n * n!)up to a small constant factor. This is fine forn <= 8. - Space:
O(n)for the current subset and permutation, sincepermutationsis lazy.
Going further
When every multiplier is at least 1, an exchange argument shows that card A should come before card B when b_A * (m_B - 1) >= b_B * (m_A - 1) with b = m - c. A single sorted order is then best for every subset, and a 0/1 knapsack over cost in that order replaces the permutation search.
Reference solution
from itertools import permutations
from typing import List
def best_final_score(cards: List[List[int]], budget: int) -> int:
n = len(cards)
best = 0 # buying nothing is always allowed
for mask in range(1, 1 << n):
chosen = [i for i in range(n) if (mask >> i) & 1]
if sum(cards[i][1] for i in chosen) > budget:
continue # over budget, ordering cannot fix this
for order in permutations(chosen):
score = 0
for i in order:
m, c = cards[i]
score = (score + 1) * m - c
if score > best:
best = score
return best