Skip to content

Commit 6bbeb7e

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 3a88e7c commit 6bbeb7e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
// Function to calculate derangements using space-optimized approach
4+
int solve(int n) {
5+
// Base case: For n = 1, there are no valid derangements
6+
if (n == 1) return 0;
7+
8+
// Base case: For n = 2, there is exactly one valid derangement
9+
if (n == 2) return 1;
10+
11+
// Initialize variables to store results for the last two states
12+
// prev: D(n-2), curr: D(n-1)
13+
int prev = 0; // D(1)
14+
int curr = 1; // D(2)
15+
16+
// Loop to calculate D(n) iteratively using the relation:
17+
// D(i) = (i-1) * (D(i-1) + D(i-2))
18+
for (int i = 3; i <= n; i++) {
19+
// Compute the next derangement value
20+
int next = (i - 1) * (curr + prev);
21+
22+
// Update prev and curr for the next iteration
23+
prev = curr;
24+
curr = next;
25+
}
26+
27+
// Return the result for D(n)
28+
return curr;
29+
}
30+
31+
// Main function to calculate derangements
32+
int countDer(int n) {
33+
// Delegate the computation to the solve function
34+
return solve(n);
35+
}
36+
};

0 commit comments

Comments
 (0)