|
| 1 | +/** |
| 2 | + * 801. Minimum Swaps To Make Sequences Increasing |
| 3 | + * https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two integer arrays of the same length nums1 and nums2. In one operation, you are |
| 7 | + * allowed to swap nums1[i] with nums2[i]. |
| 8 | + * |
| 9 | + * For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to |
| 10 | + * obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8]. |
| 11 | + * |
| 12 | + * Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The |
| 13 | + * test cases are generated so that the given input always makes it possible. |
| 14 | + * |
| 15 | + * An array arr is strictly increasing if and only if |
| 16 | + * arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} nums1 |
| 21 | + * @param {number[]} nums2 |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var minSwap = function(nums1, nums2) { |
| 25 | + let noSwap = 0; |
| 26 | + let swap = 1; |
| 27 | + |
| 28 | + for (let i = 1; i < nums1.length; i++) { |
| 29 | + let nextNoSwap = Infinity; |
| 30 | + let nextSwap = Infinity; |
| 31 | + |
| 32 | + const canKeepBoth = nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]; |
| 33 | + const canSwapBoth = nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]; |
| 34 | + |
| 35 | + if (canKeepBoth) { |
| 36 | + nextNoSwap = Math.min(nextNoSwap, noSwap); |
| 37 | + nextSwap = Math.min(nextSwap, swap + 1); |
| 38 | + } |
| 39 | + |
| 40 | + if (canSwapBoth) { |
| 41 | + nextNoSwap = Math.min(nextNoSwap, swap); |
| 42 | + nextSwap = Math.min(nextSwap, noSwap + 1); |
| 43 | + } |
| 44 | + |
| 45 | + noSwap = nextNoSwap; |
| 46 | + swap = nextSwap; |
| 47 | + } |
| 48 | + |
| 49 | + return Math.min(noSwap, swap); |
| 50 | +}; |
0 commit comments