TopCoder SRM415 div2-250. Submitted for 237 points