FunctionRacerProblemsRace

Numbers Round

MediumRecursionPython, JavaScript, TypeScript, Java, C++

You hold the number cards in cards. A step picks any two of the cards you hold, takes them away, and gives you one new card showing their sum, their product, or one of them minus the other (either way round). So 9 and 4 can become 13, 36, 5 or -5. You may keep making steps while you hold at least two cards, and you may stop at any time, even before the first step.

When you stop you show one card you hold. Return the value closest to target that you can show this way. If two values are equally close, return the smaller one.

Every step leaves one card fewer, so a recursive function that tries every pair of cards and every result, then explores the smaller hand, reaches every possibility. A loop over a list of hands still to explore works too.

Example 1

cards [3,7,2]
target 20
returns 20

Add 3 and 7 to get 10, then multiply that card by 2 to show exactly 20.

Example 2

cards [2,6]
target 10
returns 8

The hand can show 2, 6, 8, 12, 4 or -4. Both 8 and 12 are 2 away from 10, and the smaller one wins.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems