My solution to the second problem for Google Code Jam practice