|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive helper function to solve the problem |
| 4 | + // `nums1` and `nums2` are the input arrays |
| 5 | + // `index` represents the current position in the arrays |
| 6 | + // `n` is the size of the arrays |
| 7 | + // `swapped` indicates if the previous elements were swapped |
| 8 | + int solve(vector<int>& nums1, vector<int>& nums2, int index, int n, bool swapped) { |
| 9 | + // Base case: if we reach the end of the arrays, no swaps are needed |
| 10 | + if (index >= n) return 0; |
| 11 | + |
| 12 | + // Initialize the minimum swaps required as a large value |
| 13 | + int ans = INT_MAX; |
| 14 | + |
| 15 | + // Retrieve the previous elements in both arrays |
| 16 | + int prev1 = nums1[index - 1]; |
| 17 | + int prev2 = nums2[index - 1]; |
| 18 | + |
| 19 | + // If the previous elements were swapped, reverse them |
| 20 | + if (swapped) swap(prev1, prev2); |
| 21 | + |
| 22 | + // Case 1: No swap at the current index |
| 23 | + // Check if the current elements maintain the increasing order without a swap |
| 24 | + if (nums1[index] > prev1 && nums2[index] > prev2) |
| 25 | + ans = solve(nums1, nums2, index + 1, n, 0); |
| 26 | + |
| 27 | + // Case 2: Swap at the current index |
| 28 | + // Check if swapping the current elements maintains the increasing order |
| 29 | + if (nums1[index] > prev2 && nums2[index] > prev1) |
| 30 | + ans = min(ans, 1 + solve(nums1, nums2, index + 1, n, 1)); |
| 31 | + |
| 32 | + // Return the minimum number of swaps required |
| 33 | + return ans; |
| 34 | + } |
| 35 | + |
| 36 | + // Main function to find the minimum number of swaps needed |
| 37 | + int minSwap(vector<int>& nums1, vector<int>& nums2) { |
| 38 | + // Insert dummy values at the start of both arrays to simplify comparisons |
| 39 | + nums1.insert(nums1.begin(), -1); |
| 40 | + nums2.insert(nums2.begin(), -1); |
| 41 | + |
| 42 | + // Get the size of the arrays |
| 43 | + int n = nums1.size(); |
| 44 | + |
| 45 | + // Initialize the swapped flag as false |
| 46 | + bool swapped = 0; |
| 47 | + |
| 48 | + // Start solving from the first actual element |
| 49 | + return solve(nums1, nums2, 1, n, swapped); |
| 50 | + } |
| 51 | +}; |
0 commit comments