Problem 560119 · medium · Phase 05 Advanced Algorithms & Graphs

Card Purge

dynamic programming · 1-D dp · counting values · problem transformation

You hold a pile of numbered cards cards. A move is: choose a card with value v, score v points, then discard that card and every card whose value is v - 1 or v + 1 (other cards with value v stay and can be scored later). Repeat until the pile is empty. Return the maximum score.

Examples

Input:  cards = [3, 4, 2]
Output: 6
Explanation: score the 4 (discarding 3), then score the 2.

Input:  cards = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation: scoring the three 3s (9 points) discards every 2 and 4.

Constraints

  • 1 <= len(cards) <= 10**5
  • 1 <= cards[i] <= 10**5
  • Target complexity: O(n + max(cards)) or O(n log n) time.

Goals

  • Transform a value-deletion game into a take-or-skip problem over sorted values
  • Aggregate duplicates before running the recurrence
Starting Python…