Best C++ Solution || Space optimize approach
Complexity
Time complexity:O(n)

Space complexity:O(1)
Code

# Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
public:
    int Solve(vector<int>&nums1,vector<int>&nums2){
          int n=nums1.size();
          vector<int>next(2,0);
          vector<int>curr(2,0);

          for(int i=n-1; i>0; i--){
             for(int j=0; j<2; j++){
                int ans=INT_MAX;
                int prev1=nums1[i-1];
                int prev2=nums2[i-1];
                if(j) swap(prev1,prev2);

                if(nums1[i]>prev1 && nums2[i]>prev2){
                    ans=next[0];
                }
                if(nums1[i]>prev2 && nums2[i]>prev1){
                    ans=min(ans,(1+next[1]));
                }

                curr[j]=ans;
             }
             next=curr;
          }

          return min(curr[0],curr[1]);
    }

    int minSwap(vector<int>& nums1, vector<int>& nums2) {
        nums1.insert(nums1.begin(),-1);
        nums2.insert(nums2.begin(),-1);
        return Solve(nums1,nums2);
    }
};
```
['Array', 'Dynamic Programming', 'C++']