Hello I been recently solved this problem and I found a greedy solution and I don't know why is ok. I hope that any of you could explain me why it works or show me that it should not Here is my code http://mirror.codeforces.com/contest/1132/submission/51950554

It shouldn't work. Consider summing to 45 with 8 8s and 8 7s available. Your code considers sums to 40 (5 8s), 39 (4 8s 1 7), 42 (6 7s), and 43 (6 7s 1 8). The correct answer is 45, consisting of 3 7s and 3 8s.

Ok thank you very much. Now i can think on DP solution