Pizza With 3n Slices - Problem

There is a pizza with 3n slices of varying size. You and your friends will take slices of pizza as follows:

  • You will pick any pizza slice.
  • Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
  • Your friend Bob will pick the next slice in the clockwise direction of your pick.

Repeat until there are no more slices of pizza.

Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.

Input & Output

Example 1 — Basic Case
$ Input: slices = [1,2,3,4,5,6]
Output: 10
💡 Note: Pick slices 3 and 6 for maximum sum. When you pick 3, Alice gets 2, Bob gets 4. When you pick 6, Alice gets 5, Bob gets 1. Total: 3 + 6 = 9. Wait, actually picking slices with values 4 and 6 gives sum 10.
Example 2 — Larger Array
$ Input: slices = [4,1,2,5,8,3,1,9,7]
Output: 21
💡 Note: With n=3, you need to pick 3 slices. Optimal picks are slices with values 8, 9, and 4, giving sum 8 + 9 + 4 = 21.
Example 3 — Small Array
$ Input: slices = [3,1,2]
Output: 3
💡 Note: With n=1, you pick 1 slice. The maximum value slice is 3, so pick that one.

Constraints

  • 3 ≤ slices.length ≤ 500
  • slices.length % 3 == 0
  • 1 ≤ slices[i] ≤ 1000

Visualization

Tap to expand
Pizza With 3n Slices - Optimal Solution INPUT 1 2 3 4 5 6 slices array (clockwise): 1 2 3 4 5 6 n = 2, pick n slices Circular arrangement ALGORITHM STEPS 1 Convert to House Robber Non-adjacent selection in circular array problem 2 Two DP Cases Case A: indices 0 to n-2 Case B: indices 1 to n-1 3 DP Recurrence dp[i][j] = max sum picking j slices from first i DP Transition: dp[i][j] = max( dp[i-1][j], dp[i-2][j-1] + slices[i] ) 4 Take Maximum Result = max(Case A, Case B) Pick n non-adjacent slices FINAL RESULT 6 4 You pick: 6, 4 (non-adjacent) Selection: Slice 6 = 6 Slice 4 = 4 Sum = 6 + 4 OUTPUT 10 OK - Maximum Sum! Key Insight: This problem transforms into picking n non-adjacent elements from a circular array (House Robber II variant). When you pick slice[i], Alice takes slice[i-1] and Bob takes slice[i+1], so you can never pick adjacent slices. Use 2D DP: dp[i][j] = max sum when picking exactly j slices from the first i elements. Time: O(n^2), Space: O(n^2) TutorialsPoint - Pizza With 3n Slices | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen