KatInterview

Maximum Disjoint Triples Summing to 15

Dynamic ProgrammingAuto-graded · 26 test cases
MediumAuto-gradedDynamic Programmingmemoizationrecursioncombinatorics

Last updated

Find the most disjoint three-card groups that each sum to 15, using memoized search over value counts because greedy choices can block better groupings.

Maximum Disjoint Triples Summing to 15

You have a collection of cards, each showing an integer value. A move picks any three cards still in the collection whose values add up to exactly 15, removes them for good, and earns one point. You may repeat moves in any order until you choose to stop or no valid triple remains.

Return the largest total number of points that can be earned.

Each card can be used at most once. Cards with the same value are interchangeable, so two cards showing 5 are different physical cards but equivalent for scoring. A triple may contain repeated values, for example (5, 5, 5) or (1, 1, 13), as long as enough cards with that value are available.

Function

Implement max_fifteen_triples(cards), where cards is a list of integers. It returns an integer: the maximum number of disjoint triples of cards, each summing to 15.

Notes

  • A list with fewer than 3 cards scores 0.
  • Choosing a triple greedily can prevent a better overall result, so make sure your approach considers alternatives.

Constraints

  • 0 <= len(cards) <= 50
  • 1 <= cards[i] <= 14
  • The solution should run in about one second.

Examples

Example 1

Input: max_fifteen_triples([5, 5, 5, 10, 10, 10])

Output: 1

Example 2

Input: max_fifteen_triples([1, 2, 3, 4, 14, 13])

Output: 0

Hints

Hint 1

Cards with the same value are interchangeable, so you don't need to track individual cards. Describe the situation by how many cards of each value remain.

Hint 2

Greedy can fail. For [4, 4, 5, 5, 5, 6, 6], taking (5, 5, 5) first gives 1 point, but (4, 5, 6) twice gives 2. Try choices and memoize the results by remaining counts.

Hint 3

To avoid exploring the same set of triples in many orders, always look at the smallest remaining value v. Either never use that card (discard it), or use it as the smallest member of a triple (v, b, c) with v <= b <= c and v + b + c = 15.