Twenty-four
Time limit1sMemory limit128 MB
For each hand of four cards, find the largest integer value at most 24 reachable by an expression that uses all four values with +, -, *, / and only exact division.
- Level
Medium5 of 10
- Topics
- Brute force, Recursion, Math, Implementation
- Solved
- No attempts yet
Problem
Twenty-four is a popular card game for four players. Each player holds a face-down deck. On every turn all four players flip the top card of their deck face up, so the four card values are visible to everyone.
The goal is to build an arithmetic expression from the four card values (where A = 1, J = 11, Q = 12, and K = 13) that evaluates to exactly 24. For example, for the cards A, K, J, and Q one possible expression is:
((A * K) - J) * Q
((1 * 13) - 11) * 12
The first player to call out such an expression wins the turn and moves all four cards to the bottom of their deck.
A valid expression must use all four card values, combining them only with addition, subtraction, multiplication, or division, and may use parentheses to control the order of operations. You may not juxtapose cards to form multi-digit numbers (for example, the cards 2 and 4 cannot be placed side by side to form 24). Division must be exact: a non-integer quotient is forbidden anywhere, including as the value of any intermediate subexpression.
Sometimes players take a long time to reach 24, and for some hands no expression equal to 24 exists at all. Given four cards, determine the largest value not exceeding 24 that some valid expression can produce.
Input
The first line contains an integer , the number of card hands. Each hand is given on the following four lines; each of those lines holds one integer , the value of a card.
Output
For each hand, print a single line with the largest value (with ) that some valid arithmetic expression using all four card values can produce.