Rearrange given number

Given a number, rearrange it so that it is maximum within the given range of 0 … k For eg if I have the number 123 and the k is 250 ( 0 … 250) then the answer should be 231.

Any idea how we can solve this optimally?