801. Minimum Swaps To Make Sequences Increasing

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].

Return **the minimum number of needed operations to make *nums1* and nums2 strictly increasing**. The test cases are generated so that the given input always makes it possible.

An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].

  Example 1:

Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
Output: 1
Explanation: 
Swap nums1[3] and nums2[3]. Then the sequences are:
nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
which are both strictly increasing.

Example 2:

Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
Output: 1

  Constraints:

Solution

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var minSwap = function(nums1, nums2) {
  let memo = {
    true: 1,
    false: 0,
  }
  for (let index = 1; index < nums1.length; index++) {
    const current = {
      true: Infinity,
      false: Infinity,
    }
    if (nums1[index] > nums2[index - 1] && nums2[index] > nums1[index - 1]) {
      current.true = Math.min(
        current.true,
        memo.false + 1,
      )
      current.false = Math.min(
        current.false,
        memo.true,
      )
    }
    if (nums2[index] > nums2[index - 1] && nums1[index] > nums1[index - 1]) {
      current.true = Math.min(
        current.true,
        memo.true + 1,
      )
      current.false = Math.min(
        current.false,
        memo.false,
      )
    }

    memo = current
  }
  return Math.min(
    memo.false,
    memo.true,
  )
};

Explain:

nope.

Complexity: