Maximum N digit number we can make with certain number of match sticks
<p><a href="https://i.stack.imgur.com/8jNMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jNMG.png" alt="enter image description here"></a></p>

<p>The picture shows how many sticks you need to draw each of the digits.
given a number that consists of N digits. I want to move some sticks to maximize the number. I am not allowed to change the number of digits. It had to have N digits always.I cant remove any matchstick either.</p>

<p>Example:</p>

<pre><code>given 512
answer:977
given 079
answer:997
</code></pre>

<p>My solution was to count the number of matchsticks we can use. Then we start placing 9 till we run out of it. Then when we encounter that we have problem like one match stick remaining we backtrack and make a different choice for the numbers. I am not sure whether this captures all the cases.
Is there any flaw in my logic. If so what is a better way?</p>