Skip to content

Commit 3282955

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 4e2f96e commit 3282955

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
// Helper function to solve the subproblem of picking non-adjacent slices
4+
int solve(int index, int endIndex, vector<int>& slices, int n, vector<vector<int>>& dp) {
5+
// Base case: If we've chosen n slices or exceed the valid range, return 0 (no sum)
6+
if (n == 0 || index > endIndex) return 0;
7+
8+
// If the result for this subproblem has already been computed, return the cached value
9+
if (dp[index][n] != -1) return dp[index][n];
10+
11+
// Option 1: Take the slice at the current index and move two steps forward
12+
int takeSlice = slices[index] + solve(index + 2, endIndex, slices, n - 1, dp);
13+
14+
// Option 2: Skip the slice at the current index and move one step forward
15+
int noTakeSlice = 0 + solve(index + 1, endIndex, slices, n, dp);
16+
17+
// Store the result for the current subproblem in the dp table
18+
return dp[index][n] = max(takeSlice, noTakeSlice);
19+
}
20+
21+
// Main function to find the maximum sum of slices
22+
int maxSizeSlices(vector<int>& slices) {
23+
int k = slices.size(); // Total number of slices
24+
25+
// Initialize dp table for case 1 (picking slices from index 0 to k-2)
26+
vector<vector<int>> dp(k, vector<int>(k, -1));
27+
// Case 1: Exclude the last slice (pick slices from index 0 to k-2)
28+
int case1 = solve(0, k - 2, slices, k / 3, dp);
29+
30+
// Initialize dp table for case 2 (picking slices from index 1 to k-1)
31+
vector<vector<int>> dp1(k, vector<int>(k, -1));
32+
// Case 2: Exclude the first slice (pick slices from index 1 to k-1)
33+
int case2 = solve(1, k - 1, slices, k / 3, dp1);
34+
35+
// Return the maximum of the two cases
36+
return max(case1, case2);
37+
}
38+
};

0 commit comments

Comments
 (0)