- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 62 lines of C++ from the credited upstream file pizza-with-3n-slices.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 4 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 456789101112131415 1617class Solution {18public:19 int maxSizeSlices(vector<int>& slices) {20 return max(maxSizeSlicesLinear(slices, 0, slices.size() - 1),21 maxSizeSlicesLinear(slices, 1, slices.size()));22 }23 24private:25 int maxSizeSlicesLinear(const vector<int>& slices, int start, int end) {26 vector<vector<int>> dp(2, vector<int>(slices.size() / 3 + 1));27 for (int i = start; i < end; ++i) {28 for (int j = min(((i - start + 1) - 1) / 2 + 1, int(slices.size()) / 3);29 j >= 1;30 --j) {31 dp[i % 2][j] = max(dp[(i - 1 + 2) % 2][j],32 dp[(i - 2 + 2) % 2][j - 1] + slices[i]);33 }34 }35 return dp[(end - 1) % 2][slices.size() / 3];36 }37};38 394041class Solution2 {42public:43 int maxSizeSlices(vector<int>& slices) {44 return max(maxSizeSlicesLinear(slices, 0, slices.size() - 1),45 maxSizeSlicesLinear(slices, 1, slices.size()));46 }47 48private:49 int maxSizeSlicesLinear(const vector<int>& slices, int start, int end) {50 vector<vector<int>> dp(3, vector<int>(slices.size() / 3 + 1));51 for (int i = start; i < end; ++i) {52 for (int j = 1;53 j <= min(((i - start + 1) - 1) / 2 + 1, int(slices.size()) / 3);54 ++j) {55 dp[i % 3][j] = max(dp[(i - 1 + 3) % 3][j],56 dp[(i - 2 + 3) % 3][j - 1] + slices[i]);57 }58 }59 return dp[(end - 1) % 3][slices.size() / 3];60 }61};62