Greedy Card Selection with Dynamic Deck State
Data Structure DesignModel answerLast 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:
-
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.
-
Decide: Keep the card if this probability is strictly less than a given threshold. Otherwise, discard it.
-
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.
-
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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarifying the Semantics
First, establish exactly what "remaining deck" means. When examining card at position i, the remaining deck consists of all cards at positions i+1, i+2, ..., N-1. Cards already examined (kept or discarded) are no longer in the pool.
The core challenge: after removing a card from consideration, we need to quickly count how many unseen cards have values greater than a given threshold. Doing this naively (scanning the suffix each time) costs O(N²).
Key Insight: Fenwick Tree with Coordinate Compression
We can maintain a dynamic multiset of the remaining deck using a Fenwick tree (Binary Indexed Tree):
- Coordinate compression: Map card values to ranks 1, 2, ..., M where M is the number of distinct values
- Fenwick tree of counts: Track how many cards of each rank remain in the unseen portion
- Process left-to-right:
- Remove the current card from the tree
- Query the tree to count remaining cards with higher rank
- Apply the decision rules
Implementation Details
Forced selection rule: When cards_remaining == cards_needed, we must take every remaining card to reach exactly k. This prevents underselection.
Probability calculation: To avoid floating-point edge cases, instead of computing prob = better / remaining and comparing to threshold, use the equivalent integer comparison: better < threshold * remaining.
Edge case (last card): When examining the final card, remaining = 0. We define probability as 0 in this case (keep the card if needed).
Algorithm
from typing import List
def select_optimal_hand(cards: List[int], k: int, threshold: float) -> int:
n = len(cards)
if k == 0:
return 0
# Coordinate compression: map values to ranks 1..m
sorted_unique = sorted(set(cards))
value_to_rank = {val: idx + 1 for idx, val in enumerate(sorted_unique)}
m = len(sorted_unique)
# Fenwick tree for counting cards at each rank
tree = [0] * (m + 1)
def update(idx: int, delta: int) -> None:
"""Add delta to position idx"""
while idx <= m:
tree[idx] += delta
idx += idx & -idx
def prefix_sum(idx: int) -> int:
"""Sum of counts from rank 1 to idx"""
total = 0
while idx > 0:
total += tree[idx]
idx -= idx & -idx
return total
# Initialize: all cards are in the deck
for val in cards:
update(value_to_rank[val], 1)
selected_sum = 0
selected_count = 0
for i, val in enumerate(cards):
rank = value_to_rank[val]
# Remove current card from the remaining deck
update(rank, -1)
remaining_cards = n - i - 1
cards_needed = k - selected_count
cards_left_including_current = n - i
# Forced selection: must take all remaining to reach k
if cards_left_including_current == cards_needed:
should_keep = True
elif remaining_cards == 0:
# Last card: probability is defined as 0
should_keep = True
else:
# Count cards with rank strictly greater than current
cards_at_most_current_rank = prefix_sum(rank)
cards_with_greater_rank = remaining_cards - cards_at_most_current_rank
# Keep if probability < threshold
# Equivalently: cards_with_greater_rank < threshold * remaining_cards
should_keep = cards_with_greater_rank < threshold * remaining_cards
if should_keep:
selected_sum += val
selected_count += 1
if selected_count == k:
break
return selected_sum
Complexity Analysis
Time: O(N log N)
- Coordinate compression (sorting): O(N log N)
- Each of N cards requires one Fenwick update and one query: O(N log M) where M ≤ N
- Overall: O(N log N)
Space: O(N) for the rank mapping and Fenwick tree
For N = 10,000, this performs roughly 140,000 operations—easily within time limits.
Common Mistakes
- Stale counts: Computing "better" cards against the original full deck instead of the shrinking remaining deck
- Off-by-one errors: Including the current card in "remaining" or not removing it before querying
- Missing forced selection: Allowing the algorithm to select fewer than k cards
- Floating-point comparison: Using exact equality when comparing probabilities at the threshold boundary
- Division by zero: Not handling the last card case where remaining = 0
Edge Cases to Verify
- threshold = 0.0: Only forced picks occur; selects the last k cards
- threshold = 1.0: Discards a card only if all remaining cards are strictly better
- k = 1: Should select a single card according to the strategy
- Last card needed: Remaining = 0 should result in probability = 0, triggering a keep
- Duplicate values: The strict ">" comparison handles ties correctly
Example Walkthrough
For cards = [10, 5, 8, 2, 9], k = 2, threshold = 0.5:
| i | Card | Remaining | Better Count | Prob | Keep? | Sum |
|---|---|---|---|---|---|---|
| 0 | 10 | 4 | 0 | 0.0 | Yes | 10 |
| 1 | 5 | 3 | 2 | 0.67 | No | 10 |
| 2 | 8 | 2 | 1 | 0.5 | No | 10 |
| 3 | 2 | 1 | 1 | 1.0 | No | 10 |
| 4 | 9 | 0 | 0 | 0.0 | Yes | 19 |
Result: 19