values containing only the numbers 1, 2 and 3, and an array locks of the same length made of zeros and ones.
The neighbours at positions i and i + 1 may trade places only when the left one is exactly one greater than the right one (values[i] - values[i + 1] == 1) and lock i is open (locks[i] == 0). Such swaps can be made any number of times.
In one operation you can open any lock, setting locks[i] to 0. Return the fewest operations after which values can be sorted in non-decreasing order, or -1 if that is impossible even with every lock open.values=[2, 1, 3, 2], locks=[1, 0, 1, 1] → 2
The 2 and 1 at positions 0–1 must swap, so lock 0 has to be opened. The 3 and 2 at positions 2–3 must swap as well, so lock 2 is opened too. That makes 2.
values=[1, 3, 2, 1], locks=[0, 0, 0, 0] → -1
A 3 stands left of the last 1, and a 3 can never swap with a 1 directly, so sorting is impossible.
values=[1, 1, 2, 3], locks=[1, 1, 1, 1] → 0
The row is already sorted, nothing needs opening.
values=[2, 1, 3, 2], locks=[1, 0, 1, 1]
2
Run checks the first 3 tests in your browser. Submit checks all 139 tests on the server, hidden ones included.