SPRGB - Some (Pseudo) Random Guy's Blog

Advent of Code 2025 Day 3 using recursion

Problem description

Given an array of digits 1-9 bank, and a number of batteries n, where length(bank) >= n, find the maximum number that you can construct by selecting n digits from bank in order.

Examples

bank batteries value
5635 2 65
333 2 33
9819 3 989

Recursive solution

A good approach to find a recursive solution is to think of the base case and some concrete cases:

Another thing to keep in mind is which maximum value to choose from. Consider bank = 8781, n = 2, where the result should be 88. On the first iteration the maximum digit is 8 and you have two options:

Therefore, you always have to choose the first occurrence of the maximum digit.

The algorithm then would be the following

  1. If n = 0 return 0.
  2. If n = 1 return the maximum digit.
  3. If n > 1 select the maximum digit from the array excluding the last n - 1 digits.
  4. Call the function again with the remainder of the bank array and n = n - 1.

For accumulating the result there are three choices:

Since the solution is in Rust, which doesn’t have stable tail-call optimization yet, it uses the third option, however it’s trivial to convert it to a tail-call optimized case by adding an accumulator as an argument.