Skip to content

Commit 4e2f96e

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 58b9942 commit 4e2f96e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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) {
5+
// Base case: If we've chosen n slices or we exceed the valid range, return 0 (no sum)
6+
if (n == 0 || index > endIndex) return 0;
7+
8+
// Option 1: Take the slice at the current index and move two steps forward
9+
int takeSlice = slices[index] + solve(index + 2, endIndex, slices, n - 1);
10+
11+
// Option 2: Skip the slice at the current index and move one step forward
12+
int noTakeSlice = 0 + solve(index + 1, endIndex, slices, n);
13+
14+
// Return the maximum of taking or skipping the current slice
15+
return max(takeSlice, noTakeSlice);
16+
}
17+
18+
// Main function to find the maximum sum of slices
19+
int maxSizeSlices(vector<int>& slices) {
20+
int k = slices.size(); // Total number of slices
21+
// Case 1: Exclude the last slice (pick slices from index 0 to k-2)
22+
int case1 = solve(0, k - 2, slices, k / 3);
23+
24+
// Case 2: Exclude the first slice (pick slices from index 1 to k-1)
25+
int case2 = solve(1, k - 1, slices, k / 3);
26+
27+
// Return the maximum of the two cases
28+
return max(case1, case2);
29+
}
30+
};

0 commit comments

Comments
 (0)