KatInterview

Greedy Card Selection with Dynamic Deck State

Data Structure DesignModel answer
MediumModel answerData Structure Designfenwick-treegreedysimulation

Last updated

Simulate a threshold-based card selection strategy that accounts for a shrinking deck, tracking which cards remain available after each decision.

Problem

You're implementing a card selection simulator. Given a deck of N cards with distinct integer values, you'll process them left-to-right and decide whether to keep or discard each one. Your goal is to select exactly k cards using a probability-based threshold strategy.

Selection Rules

As you examine each card in order:

  1. Calculate probability: Look at all cards you haven't seen yet (the "remaining deck"). Count how many have strictly greater value than the current card. The probability is this count divided by the total remaining cards.

  2. Decide: Keep the card if this probability is strictly less than a given threshold. Otherwise, discard it.

  3. Force selection: If the number of cards left to examine (including the current one) equals the number of cards you still need to reach k, you must keep the current card regardless of probability.

  4. Stop: Once you've kept k cards, stop immediately and return their sum.

Function Signature

def select_optimal_hand(cards: List[int], k: int, threshold: float) -> int:
    """
    cards: List of integers (card values)
    k: Number of cards to select
    threshold: Probability threshold (0.0 to 1.0)
    Returns: Sum of selected card values
    """

Example

Input: cards = [10, 5, 8, 2, 9], k = 2, threshold = 0.5

Processing:

  • Card 10: Remaining deck is [5, 8, 2, 9]. Zero cards are greater than 10. Probability = 0/4 = 0.0 < 0.5 → Keep
  • Card 5: Remaining deck is [8, 2, 9]. Two cards (8, 9) are greater than 5. Probability = 2/3 ≈ 0.67 ≥ 0.5 → Discard
  • Card 8: Remaining deck is [2, 9]. One card (9) is greater than 8. Probability = 1/2 = 0.5 ≥ 0.5 → Discard
  • Card 2: Remaining deck is [9]. One card is greater than 2. Probability = 1/1 = 1.0 ≥ 0.5 → Discard
  • Card 9: No cards remaining. Probability = 0/0 = 0.0 < 0.5 → Keep

Output: 10 + 9 = 19

Constraints

  • 1 ≤ N ≤ 10,000
  • 1 ≤ k < N
  • 0.0 ≤ threshold ≤ 1.0
  • Your solution should run in better than O(N²) time

Hints

Hint 1

The 'remaining deck' changes after each card is examined—you need to efficiently track which cards are still unseen

Hint 2

Counting how many remaining cards exceed a given value is a dynamic range query problem

Hint 3

Consider coordinate compression combined with a data structure that supports both point updates and prefix sums

Hint 4

The forced selection rule ensures you always select exactly k cards—handle the case where cards_remaining equals cards_needed