[LeetCode] Minimum Swaps To Make Sequences Increasing

801. Minimum Swaps To Make Sequences Increasing

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].

For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
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].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int dp[100001][2];
int solution(vector<int>& v1, vector<int>& v2, int p, bool sw) {
if(dp[p][sw] != -1) return dp[p][sw];
dp[p][sw] = 9999999;

if(v1[p] < v1[p + 1] and v2[p] < v2[p + 1]) {
dp[p][sw] = min(dp[p][sw], solution(v1,v2,p+1,false));
}

if(v1[p] < v2[p + 1] and v2[p] < v1[p + 1]) {
swap(v1[p+1], v2[p+1]);
dp[p][sw] = min(dp[p][sw], solution(v1,v2,p+1,true) + 1);
swap(v1[p+1], v2[p+1]);
}
return dp[p][sw];
}
public:
int minSwap(vector<int>& nums1, vector<int>& nums2) {
memset(dp,-1,sizeof(dp));
vector<int> v1{-1}, v2{-1};
v1.insert(v1.end(), nums1.begin(), nums1.end());
v2.insert(v2.end(), nums2.begin(), nums2.end());
dp[v1.size() - 1][0] = dp[v1.size() - 1][1] = 0;
return solution(v1,v2,0,false);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/minimum-swaps-to-make-sequences-increasing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.