|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to solve the problem of picking non-adjacent slices |
| 4 | + int solve(vector<int>& slices) { |
| 5 | + int k = slices.size(); // Total number of slices (3 * n) |
| 6 | + |
| 7 | + // Initialize two DP tables: |
| 8 | + // dp[i][n] stores the maximum sum of slices we can pick from index i with n slices left to pick. |
| 9 | + vector<vector<int>> dp(k + 2, vector<int>(k, 0)); // For the first case, we exclude the last slice |
| 10 | + vector<vector<int>> dp1(k + 2, vector<int>(k, 0)); // For the second case, we exclude the first slice |
| 11 | + |
| 12 | + // DP for case 1 (excluding the last slice) |
| 13 | + for (int index = k - 2; index >= 0; index--) { // Iterate backwards through the slices (0 to k-2) |
| 14 | + for (int n = 1; n <= k / 3; n++) { // Iterate through the number of slices left to pick |
| 15 | + // Option 1: Take the current slice and move 2 steps forward (to avoid picking adjacent slices) |
| 16 | + int takeSlice = slices[index] + dp[index + 2][n - 1]; |
| 17 | + |
| 18 | + // Option 2: Skip the current slice and move 1 step forward |
| 19 | + int noTakeSlice = 0 + dp[index + 1][n]; |
| 20 | + |
| 21 | + // Store the maximum of the two options (take or skip) |
| 22 | + dp[index][n] = max(takeSlice, noTakeSlice); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // Store the result for case 1, excluding the last slice |
| 27 | + int case1 = dp[0][k / 3]; // We start from index 0 and need to pick k/3 slices |
| 28 | + |
| 29 | + // DP for case 2 (excluding the first slice) |
| 30 | + for (int index = k - 1; index >= 1; index--) { // Iterate backwards through the slices (1 to k-1) |
| 31 | + for (int n = 1; n <= k / 3; n++) { // Iterate through the number of slices left to pick |
| 32 | + // Option 1: Take the current slice and move 2 steps forward |
| 33 | + int takeSlice = slices[index] + dp1[index + 2][n - 1]; |
| 34 | + |
| 35 | + // Option 2: Skip the current slice and move 1 step forward |
| 36 | + int noTakeSlice = 0 + dp1[index + 1][n]; |
| 37 | + |
| 38 | + // Store the maximum of the two options (take or skip) |
| 39 | + dp1[index][n] = max(takeSlice, noTakeSlice); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // Store the result for case 2, excluding the first slice |
| 44 | + int case2 = dp1[1][k / 3]; // We start from index 1 and need to pick k/3 slices |
| 45 | + |
| 46 | + // Return the maximum of the two cases |
| 47 | + return max(case1, case2); |
| 48 | + } |
| 49 | + |
| 50 | + // Main function to calculate the maximum sum of slices |
| 51 | + int maxSizeSlices(vector<int>& slices) { |
| 52 | + return solve(slices); // Call the solve function to compute the result |
| 53 | + } |
| 54 | +}; |
0 commit comments