801. Minimum Swaps To Make Sequences Increasing
Example:
Input: A = [1,3,5,4], B = [1,2,3,7]
Output: 1
Explanation:
Swap A[3] and B[3]. Then the sequences are:
A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
which are both strictly increasing.// Dynamic Programming
int minSwap(vector<int>& A, vector<int>& B) { // time: O(n); space: O(n)
int n = A.size();
vector<int> swap(n), fix(n);
swap[0] = 1;
for (int i = 1; i < n; ++i) {
if (A[i - 1] >= B[i] || B[i - 1] >= A[i]) { // (2) same as the previous manipulation
swap[i] = swap[i - 1] + 1;
fix[i] = fix[i - 1];
} else if (A[i - 1] >= A[i] || B[i - 1] >= B[i]) { // (3) oppotite to the previous manipuliation
swap[i] = fix[i - 1] + 1;
fix[i] = swap[i - 1];
} else { // (1) either swap or fix is okay
int mn = min(swap[i - 1], fix[i - 1]);
swap[i] = mn + 1;
fix[i] = mn;
}
}
return min(swap.back(), fix.back());
}Last updated