FastPrepConcurrent Discounted Card Purchases
Problem · Simulation

Concurrent Discounted Card Purchases

Learn this problem
MediumBrex logoBrexFULLTIMEPHONE SCREEN

Problem statement

A player has gem balances in the fixed color order [B,W,G,R,Y]. Each row cards[i] is [rewardColor,costB,costW,costG,costR,costY], where rewardColor is an index from 0 through 4.

The player may own multiple copies of a card. Before a purchase, each already-owned card of color c discounts that purchase's cost in color c by one gem, but a cost never falls below zero.

Each request is [expectedVersion,cardIndex]. Requests are serialized in array order for this player. Return -1 for a version conflict, 0 when the discounted card is unaffordable, and 1 after an atomic purchase. Only a successful purchase deducts gems, adds the card, and increments the version.

Return all request status codes followed by the final version, five final gem balances, and five owned-card counts, all in [B,W,G,R,Y] order.

Function

processPurchases(gems: int[], cards: int[][], requests: int[][]) → int[]

Examples

Example 1

gems = [3,3,0,0,0]cards = [[0,2,1,0,0,0],[1,2,2,0,0,0]]requests = [[0,0],[0,1],[1,1]]return = [1,-1,1,2,0,0,0,0,0,1,1,0,0,0]

The first purchase succeeds and advances the version to 1. The stale second request conflicts. The last request uses the blue-card discount and succeeds.

Example 2

gems = [0,0,0,0,0]cards = [[4,1,0,0,0,0]]requests = [[0,0]]return = [0,0,0,0,0,0,0,0,0,0,0,0]

The card is unaffordable, so every part of the player state remains unchanged.

Constraints

  • gems.length = 5 and 0 <= gems[c] <= 10^9.
  • 1 <= cards.length, requests.length <= 10^5.
  • Every card row has six integers; its reward color and every request card index are valid.
  • Every base cost is between 0 and 10^9.
  • Every expected version is between 0 and the number of requests.
drafts saved locally
public int[] processPurchases(int[] gems, int[][] cards, int[][] requests) {
    // Write your code here.
}
gems[3,3,0,0,0]
cards[[0,2,1,0,0,0],[1,2,2,0,0,0]]
requests[[0,0],[0,1],[1,1]]
expected[1,-1,1,2,0,0,0,0,0,1,1,0,0,0]
checking account