N = gets.to_i S = N.to_s A = S.chars p (0...S.size-2).inject(N){|r, i| s = S.dup a = A[i + 1..-1] j = i + 1 + a.rindex(a.max) s[i], s[j] = s[j], s[i] [r, s.to_i].max }