Sponsored
Sponsored
Solve with full IDE support and test cases
Use these hints if you're stuck. Try solving on your own first.
Consider how to calculate the minimum number of operations when <code>nums1[n - 1]</code> and <code>nums2[n - 1]</code> are fixed (they are not swapped).
For each index <code>i</code>, there are only <code>3</code> possibilities: <ul> <li><code>nums1[i] <= nums1[n - 1] && nums2[i] <= nums2[n - 1]</code>. We don't need to swap them.</li> <li><code>nums1[i] <= nums2[n - 1] && nums2[i] <= nums1[n - 1]</code>. We have to swap them.</li> <li>Otherwise, there is no solution.</li> </ul>
There are <code>2</code> cases to determine the minimum number of operations: <ul> <li>The first case is the number of indices that need to be swapped when <code>nums1[n - 1]</code> and <code>nums2[n - 1]</code> are fixed.</li> <li>The second case is <code>1 +</code> the number of indices that need to be swapped when <code>nums1[n - 1]</code> and <code>nums2[n - 1]</code> are swapped.</li> </ul>
The answer is the minimum of both cases or <code>-1</code> if there is no solution in either case.