Yordi - A Lifelong Journey of Growth

Advent of Code 2025 - Day 3

Advent of Code day 3. Back at it!

Check out my full solution for day 3 at GitHub.

The meat of today's problem is in finding the largest possible number in a list by combining two (part one) or twelve (part two) numbers in order.

Let's look at an example:

234234234234278

If we were to find the largest possible number consisting of two digits, we would end up with 78. While 8 is the largest number in this list and seems like the best option as first digit of our number, it is a faulty option because it is at the end of the list. That means we cannot add another digit after 8, as there is none. So, we first go for the second largest number in this list (7) and then search for the next largest number in the remainder of the list (after the 7).

This principle is the main idea for solving this problem. In general, if we need to find the largest possible number consisting of x digits, we first look for the largest number in the list excluding the last x - 1 digits. For example, if we need to find the largest possible number consisting of 12 digits, we first look for the largest number in the list excluding the last 11 digits. For the second digit of the resulting number, we look in the list excluding the last 10 digits, but we also start one position after the index of the previously found digit. That way we make sure we never look to the left side of the previously found digit, and we also leave enough room at the end of the list to find new digits.

In code, this logic looks as follows:

def calculate_joltage(banks: List[List[int]], nr_of_batteries: int) -> int:
    total_joltage = 0
    for bank in banks:
        joltage = ""
        max_index = 0
        for i in range(1, nr_of_batteries + 1):
            end_index = -(nr_of_batteries - i) if (nr_of_batteries - i) != 0 else len(bank)
            max_battery = max(bank[max_index:end_index])
            max_index = bank[max_index:end_index].index(max_battery) + max_index + 1
            joltage += str(max_battery)
        total_joltage += int(joltage)
    return total_joltage

As we need to build up a number out of many digits, I represent the number as a string so that I concatenate new digits to it easily. In each iteration, I look for the largest number starting one position after the digit we found in the previous iteration and also ignore the last digits to leave room for future iterations.

As the logic for part one and part two is the same, I can just call the function with value 2 for nr_of_batteries in part one and with value 12 in part two.