
The Problem
You have banks of batteries, each represented as a line of digits. You need to turn on exactly k batteries to produce the largest possible joltage. The joltage is the number formed by the digits of the batteries you turn on, in their original order (no rearranging!).
Summary
Part | Question | Strategy |
|---|---|---|
1 | Largest joltage with 2 batteries | Try each position as first digit, pair with max after |
2 | Largest joltage with 12 batteries | Greedy selection: pick max digit in valid range, repeat |
Part 1: Pick 2 Batteries
Goal: Find the two digits (in order) that form the largest 2-digit number.
The Tricky Part
The key insight is that we can't just find the two largest digits - we must respect the ordering constraint.
Consider 818181911112111:
The largest digits are
9and8But the
9is at position 6, and there's no8after itThe best digit after
9is2(at position 11)So the answer is
92, not98!
Try every position as the first digit, pair it with the maximum digit that comes after:
For Part 1, I just went with the simplest approach that works. It's O(n²) but n is small, so…
Part 2: Pick 12 Batteries
Now we need to select 12 digits. The brute-force approach (try all combinations) would be astronomical. Time for a smarter strategy!
The Greedy Insight
To maximize a number, we want the leftmost digits to be as large as possible. This suggests a greedy approach:
For the 1st digit: pick the max from a range that leaves 11 digits remaining
For the 2nd digit: pick the max from positions after our 1st pick, leaving 10 remaining
...and so on
The Valid Range
If we have n digits and need to pick k, when choosing the i-th digit:
Start: right after our previous pick (
prevPos + 1)End: position
n - k + i(must leave enough digits for remaining picks)
Why BigInt?
12-digit numbers like 987654321111 exceed JavaScript's safe integer limit (Number.MAX_SAFE_INTEGER ≈ 9 quadrillion). We use BigInt to avoid precision loss when summing.
The Refactor: One Function to Rule Them All
Since both parts use the same greedy algorithm (just with different k values), I unified them into a single solve(lines, k) function!