Sesos, 58 55 bytes
0000000: 16e0d7 bdcdf8 8cdf1b e6cfbb 840d3f bf659b 38e187 ..............?.e.8..
0000015: f8639b 39dc37 fc893f 666c05 7e7ed9 b88b3f ae0d3f .c.9.7..?fl.~~...?..?
000002a: 676ed8 bd9940 7fdc3b 36619e f1 gn...@..;6a..
Handles inputs up to 400 reasonably well, but run time increases dramatically after that point.
Try it online! Check Debug to see the generated SBIN code.
Sesos assembly
The binary file above has been generated by assembling the following SASM code.
set numin, set numout
get
jmp
jmp
rwd 3, add 1, rwd 1, add 1, fwd 4, sub 1
jnz
rwd 3, sub 1
jnz
rwd 3, add 1, fwd 2
jmp
rwd 1, sub 1, fwd 3, sub 1, fwd 2, add 3
jmp
rwd 2
jmp
rwd 3
jnz
fwd 6, get, rwd 4, sub 1
jmp
fwd 1, sub 1
jmp
rwd 3
jnz
sub 1
jmp
fwd 3
jnz
rwd 4, sub 1
jnz
fwd 1
jmp
rwd 1, add 1, fwd 1, add 1
jnz
sub 1, fwd 3, sub 1
jmp
fwd 3
jnz
rwd 1, sub 1
jnz
rwd 2, get
nop
rwd 3
jnz
fwd 3, get, rwd 2
jmp
fwd 2, add 1
jmp
fwd 3
jnz
rwd 1, add 1, rwd 2
jmp
rwd 3
jnz
fwd 1, sub 1
jnz
fwd 2
jmp
rwd 2, add 1, fwd 2, sub 1
jnz
nop
get, fwd 3
jnz
rwd 1, add 1, fwd 2
jnz
rwd 2, sub 1
jmp
rwd 1, sub 1, fwd 1, sub 1
jnz
rwd 1, put