You are playing a gem-trading card game. You have a list gems where gems[i] is the number of gems of color i you currently own. You are also given a list of cards, and each card has two fields:
-
cost
: a list of integers where
cost[j]
is the number of gems of color
j
required to buy the card.
-
color
: an integer, the color of the card itself.
Cards must be bought in the order they appear. For each card, try to buy it with your current gems. A discount applies: for every card of color X you already own, the number of color X gems any later card costs is reduced by 1, and an effective cost never goes below 0.
After processing all cards in order (buying each one you can afford and skipping the ones you cannot), return the total number of cards you bought.
Function Signature
def count_purchased_cards(gems: list[int], cards: list[dict]) -> int:
Rules
-
Each card is a dict
{"cost": [...], "color": c}
with
len(cost) == len(gems)
.
-
When you own
discount[j]
cards of color
j
, a card's effective cost in color
j
is
max(0, cost[j] - discount[j])
.
-
You can afford a card when your gems cover its effective cost in every color. Buying it subtracts the effective cost from your gems and adds 1 to the discount for the card's own color.
-
A card's discount applies only to cards that come after it, never to its own price.
-
Each card is considered exactly once. A skipped card is not revisited, even if later discounts would make it affordable.
Constraints
-
1 <= len(gems) <= 5
-
0 <= gems[i] <= 100
-
1 <= len(cards) <= 1000
-
len(cards[i]["cost"]) == len(gems)
-
0 <= cards[i]["cost"][j] <= 100
-
0 <= cards[i]["color"] < len(gems)
Examples
Input: gems = [3, 3, 3], cards = [{"cost": [1, 1, 0], "color": 0}, {"cost": [1, 0, 1], "color": 0}, {"cost": [2, 1, 1], "color": 1}]
Output: 3
Card 0 costs [1, 1, 0] and leaves [2, 2, 3], and card 1 gets one color-0 discount, so it costs [0, 0, 1] and leaves [2, 2, 2]. With two color-0 cards owned, card 2 costs [0, 1, 1] and leaves [2, 1, 1], so all 3 cards are bought.
Input: gems = [5, 0, 0], cards = [{"cost": [2, 0, 0], "color": 0}, {"cost": [2, 0, 0], "color": 0}, {"cost": [2, 0, 0], "color": 1}]
Output: 3
Card 0 costs [2, 0, 0] and leaves [3, 0, 0], and card 1 costs [1, 0, 0] after one discount and leaves [2, 0, 0]. Card 2 has two color-0 discounts, so it is free, and all 3 cards are bought.
Input: gems = [2, 1], cards = [{"cost": [3, 0], "color": 1}, {"cost": [1, 1], "color": 0}, {"cost": [2, 0], "color": 0}]
Output: 2
Card 0 needs 3 color-0 gems and you hold 2, so it is skipped and never reconsidered. Card 1 costs [1, 1] and leaves [1, 0], and its discount drops card 2's cost to [1, 0], which leaves [0, 0], so 2 cards are bought.