Solution for problem 7, not fully optimal, but computes under a minute.