Minimum Swaps To Make Sequences Increasing in C++


Suppose we have two integer sequences A and B of the same non-zero length. We can swap elements A[i] and B[i]. We have to keep in mind that both elements are in the same index position in their respective sequences. After completing some number of swaps, A and B are both strictly increasing. We have to find the minimum number of swaps to make both sequences strictly increasing.

So if the input is like A = [1,3,5,4] and B = [1,2,3,7], then the answer will be 1, if we swap A[3] with B[3], then the sequences will be A = [1,3,5,7] and B = [1,2,3,4], both are strictly increasing.

To solve this, we will follow these steps −

  • n := size of A array, make two arrays swapCnt and noSwapCnt of size n each

  • insert 1 into swapCnt and 0 into noSwapCnt

  • for i in range 1 to n – 1

    • swapCnt[i] := n and noSwapCnt := n

    • if A[i] > A[i – 1] AND B[i] > B[i – 1], then

      • noSwapCnt[i] := noSwapCnt[i – 1]

      • swapCnt[i] := swapCnt[i – 1] + 1

    • if A[i] > B[i – 1] and B[i] > A[i – 1], then

      • swapCnt[i] := minimum of swapCnt[i], 1 + noSwapCnt[i – 1]

      • noSwapCnt[i] := minimum of swapCnt[i – 1], noSwapCnt[i]

  • return minimum of swapCnt[n – 1], noSwapCnt[n – 1]

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minSwap(vector<int>& A, vector<int>& B) {
      int n = A.size();
      vector <int> swapCnt(n), noSwapCnt(n);
      swapCnt[0] = 1;
      noSwapCnt[0] = 0;
      for(int i = 1; i < n; i++){
         swapCnt[i] = n;
         noSwapCnt[i] = n;
         if(A[i] > A[i - 1] && B[i] > B[i - 1]){
            noSwapCnt[i] = noSwapCnt[i - 1];
            swapCnt[i] = swapCnt[i - 1] + 1;
         }
         if(A[i] > B[i - 1] && B[i] > A[i - 1]){
            swapCnt[i] = min(swapCnt[i], 1 + noSwapCnt[i - 1]);
            noSwapCnt[i] = min(swapCnt[i - 1], noSwapCnt[i]);
         }
      }
      return min(swapCnt[n - 1], noSwapCnt[n - 1]);
   }
};
main(){
   vector<int> v1 = {1,3,5,4};
   vector<int> v2 = {1,2,3,7};
   Solution ob;
   cout << (ob.minSwap(v1, v2));
}

Input

[1,3,5,4]
[1,2,3,7]

Output

1

Updated on: 02-May-2020

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements