Skip to content

Commit 551fa4c

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 1d7aa69 commit 551fa4c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution
2+
{
3+
public:
4+
// Recursive function with memoization to calculate the maximum number of cuts
5+
int solve(int n, int x, int y, int z, vector<int>& dp){
6+
// Base case: If the length is exactly 0, no further cuts are needed
7+
if(n == 0) return 0;
8+
// Base case: If the length becomes negative, this is an invalid case
9+
if(n < 0) return INT_MIN;
10+
11+
// If the result for the current length `n` is already computed, return it
12+
if(dp[n] != -1) return dp[n];
13+
14+
// Try cutting a segment of length x and recursively calculate the cuts
15+
int a = solve(n-x, x, y, z, dp) + 1;
16+
// Try cutting a segment of length y and recursively calculate the cuts
17+
int b = solve(n-y, x, y, z, dp) + 1;
18+
// Try cutting a segment of length z and recursively calculate the cuts
19+
int c = solve(n-z, x, y, z, dp) + 1;
20+
21+
// Store the result in the dp array for future use
22+
dp[n] = max(a, max(b, c));
23+
24+
// Return the computed result for the current length `n`
25+
return dp[n];
26+
}
27+
28+
// Function to find the maximum number of cuts that can be made
29+
int maximizeTheCuts(int n, int x, int y, int z)
30+
{
31+
// Create a dp array initialized with -1 to indicate uncomputed states
32+
vector<int> dp(n+1, -1);
33+
34+
// Call the recursive function with memoization to calculate the maximum cuts
35+
int maxCuts = solve(n, x, y, z, dp);
36+
37+
// If the result is negative, it means no valid cuts are possible
38+
if(maxCuts < 0) return 0;
39+
40+
// Return the maximum number of valid cuts
41+
return maxCuts;
42+
}
43+
};

0 commit comments

Comments
 (0)