Let's make this one less mysterious. For 1388. Pizza With 3n Slices, the solution in this repository is mainly a dynamic programming solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: dynamic programming, two pointers.
The notes already sitting in the source point us in the right direction:
- https://leetcode.com/problems/pizza-with-3n-slices/discuss/547699/C%2B%2B-Simple-DP
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxSizeSlices.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//https://leetcode.com/problems/pizza-with-3n-slices/discuss/547699/C%2B%2B-Simple-DP
02//Runtime: 24 ms, faster than 27.27% of C++ online submissions for Pizza With 3n Slices.
03//Memory Usage: 12.4 MB, less than 100.00% of C++ online submissions for Pizza With 3n Slices.
04class Solution {
05public:
06 int maxSizeSlices(vector<int>& slices, int l, int r){
07 //l and r are inclusive
08 int N = slices.size();
09 int k = N/3; //we can take k pieces
10 vector<vector<int>> dp(N, vector<int>(k, 0));
11
12 for(int i = l; i <= r; i++){
13 for(int j = 0; j < k; j++){
14 /*
15 1. don't take current piece
16 2. take current piece, plus the value when we take (j-1)th piece of cake at position (i-2)
17 */
18 dp[i][j] = max((i-1 >= 0 ? dp[i-1][j] : 0),
19 (((i-2 >= 0) && (j-1 >= 0)) ? dp[i-2][j-1] : 0) + slices[i]);
20 }
21 }
22
23 return dp[r][k-1];
24 };
25
26 int maxSizeSlices(vector<int>& slices) {
27 int N = slices.size();
28 return max(maxSizeSlices(slices, 0, N-2),
29 maxSizeSlices(slices, 1, N-1));
30 }
31};
Cost