Skip to content

Commit ca15d21

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent da74af1 commit ca15d21

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
public:
3+
// Function to solve the problem iteratively using bottom-up dynamic programming
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 whether the elements were swapped
8+
int solve(vector<int>& nums1, vector<int>& nums2, int index, int n, bool swapped) {
9+
// Create a DP table with dimensions [n+1][2]
10+
// `dp[i][0]` represents the minimum swaps required starting at index `i` when no swap is made at `i-1`
11+
// `dp[i][1]` represents the same but when a swap is made at `i-1`
12+
vector<vector<int>> dp(n + 1, vector<int>(2, 0));
13+
14+
// Start filling the DP table from the last index towards the first
15+
for (int index = n - 1; index >= 1; index--) {
16+
for (int swapped = 1; swapped >= 0; swapped--) {
17+
int ans = INT_MAX; // Initialize the minimum swaps for the current state to a large value
18+
19+
// Determine the previous elements
20+
int prev1 = nums1[index - 1];
21+
int prev2 = nums2[index - 1];
22+
23+
// If the previous state involved a swap, adjust `prev1` and `prev2`
24+
if (swapped) swap(prev1, prev2);
25+
26+
// Case 1: No swap at the current index
27+
// Check if the current elements maintain the increasing order without a swap
28+
if (nums1[index] > prev1 && nums2[index] > prev2)
29+
ans = dp[index + 1][0];
30+
31+
// Case 2: Swap at the current index
32+
// Check if swapping the current elements maintains the increasing order
33+
if (nums1[index] > prev2 && nums2[index] > prev1)
34+
ans = min(ans, 1 + dp[index + 1][1]);
35+
36+
// Store the result in the DP table for the current index and swap state
37+
dp[index][swapped] = ans;
38+
}
39+
}
40+
41+
// Return the minimum swaps required starting from the first actual element without a swap
42+
return dp[1][0];
43+
}
44+
45+
// Main function to find the minimum number of swaps needed
46+
int minSwap(vector<int>& nums1, vector<int>& nums2) {
47+
// Insert dummy values at the start of both arrays to simplify comparisons
48+
nums1.insert(nums1.begin(), -1);
49+
nums2.insert(nums2.begin(), -1);
50+
51+
// Get the size of the arrays
52+
int n = nums1.size();
53+
54+
// Initialize the process by calling the iterative DP function
55+
bool swapped = 0;
56+
return solve(nums1, nums2, 1, n, swapped);
57+
}
58+
};

0 commit comments

Comments
 (0)