Day 3
Day 3
I decided to use Go this time because why not - I wanted to try a compiled, simple language for string processing and see how slices and a greedy approach perform.
how I solved it
Each input line is a bank of batteries (a string of digits). For a given k, I needed the largest possible number that can be formed by selecting exactly k digits while preserving their order.
I solved it with a straightforward greedy scan: to pick each digit I scan the portion of the string that still allows enough remaining digits to fill the rest, choose the largest digit in that window, lock it in, move the start position past it, and repeat until I have k digits. This gives the lexicographically largest subsequence of length k, which is exactly the largest "joltage".
implementation
I used k = 2 for part one and k = 12 for part two.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
total :=0
for scanner.Scan() {
line := scanner.Text()
n := len(line)
k := 12
result := make([]byte, 0,20)
start := 0
for k > 0 {
maxDigit := -1
maxIndex := start
end := n - k
for i := start; i <= end; i++ {
d := int(line[i] - '0')
if d > maxDigit {
maxDigit = d
maxIndex = i
}
}
result = append(result, byte(maxDigit)+'0')
start = maxIndex + 1
k--
}
val, err := strconv.Atoi(string(result))
if err != nil {
panic(err)
}
total += val
}
fmt.Println(total)
}