Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would iterate over the array starting on the right end. Store the digit on the right as the smallest digit and max digit and start moving left, if you hit a new smaller number, call it potential smallest. If you keep moving left and you find a smaller number, make the smaller one the potential. If you find a bigger number, make potential smaller the smallest int and store the bigger one as max digit. Every time you hit a bigger digit than your smallest one, make it the new max digit. If you hit the end, swap max digit and smallest digit. In python (This works and is O(n))</p> <pre class="lang-py prettyprint-override"><code>def swap_max(digits): i = len(digits) - 1 while i &gt; 0: if digits[i] == 0: i-= 1 else: break max_i = i min_i = i pot_i = i z_i = -1 nz_i = i i = len(digits) - 1 while i &gt;= 0: if digits[i] &gt; digits[pot_i]: max_i = i min_i = pot_i if digits[i] &lt; digits[min_i] and digits[i] != 0: pot_i = i if digits[i] == 0 and z_i == -1: z_i = i if digits[i] != 0 and i &gt; 0: nz_i = i i -= 1 if z_i != -1 and max_i != 0 and max_i &lt; z_i: min_i = z_i i = nz_i max_i = i elif max_i == min_i and z_i != -1: i = nz_i if i &lt; z_i: min_i = z_i max_i = i v = digits[min_i] digits[min_i] = digits[max_i] digits[max_i] = v return digits #TESTING THE FUNCTION tests = [93561,596,10234,120,10091,98761111,1001,1010,1103,120,93218910471211292416] results = [13569,569,10234,102,10019,18761119,1001,1001,1013,102,13218910471211292496] tests = map(list,map(str,tests)) results = map(list,map(str,results)) for i in range(len(tests)): res ="".join(map(str,swap_max(map(int,tests[i])))) print res,"".join(results[i]) if res=="".join(results[i]): print "PASSED\n" else: print "FAILED\n" </code></pre> <p>This ended up working for all the examples. It also has the advantage of being O(1) memory usage.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload