Pizza With 3n Slices - Problem
Pizza With 3n Slices

Imagine you're at a pizza party with your friends Alice and Bob! There's a circular pizza cut into 3n slices of varying sizes, arranged in clockwise order. The three of you will take turns picking slices according to these rules:

๐Ÿ“ Game Rules:
1. You pick any slice from the pizza
2. Alice immediately takes the slice counterclockwise from your pick
3. Bob immediately takes the slice clockwise from your pick
4. This continues until all slices are taken

Since the pizza is circular, when you pick a slice, the adjacent slices are automatically taken by your friends, and those three slices are removed from the pizza. The remaining slices form a new circular arrangement.

๐ŸŽฏ Goal: Maximize the total sum of slice sizes that you can obtain.

Input: An integer array slices representing the sizes of pizza slices in clockwise order
Output: The maximum possible sum of slice sizes you can pick

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,3,4,5,6]
โ€บ Output: 10
๐Ÿ’ก Note: Pick slice 2 (size 3): Alice gets slice 1 (size 2), Bob gets slice 3 (size 4). Remaining: [1,5,6]. Pick slice 5 (size 6): Alice gets slice 6 (size 1), Bob gets slice 4 (size 5). Total: 3 + 6 = 9. But optimal is picking slices with values 4 and 6 for total 10.
example_2.py โ€” Larger Array
$ Input: [8,9,8,6,1,1]
โ€บ Output: 16
๐Ÿ’ก Note: With 6 slices, we pick 2. Optimal strategy picks the slices with sizes 8 and 8, avoiding adjacent selections. Total: 8 + 8 = 16.
example_3.py โ€” Small Case
$ Input: [4,1,2]
โ€บ Output: 4
๐Ÿ’ก Note: With 3 slices, we pick 1. The best choice is the slice with size 4, giving us a total of 4.

Constraints

  • 1 โ‰ค slices.length โ‰ค 500
  • slices.length % 3 == 0
  • 1 โ‰ค slices[i] โ‰ค 103
  • The number of slices is always divisible by 3

Visualization

Tap to expand
๐Ÿ• Pizza Strategy898611๐ŸŸข Your picks (sum=16)๐Ÿ”ด Friends get adjacent๐Ÿ”ต Available choicesTransform to Linear DP:Case 1: [9,8,6,1,1] โ†’ Rob 2 housesCase 2: [8,9,8,6,1] โ†’ Rob 2 housesAnswer: max(Case1, Case2) = 16
Understanding the Visualization
1
Identify Pattern
Realize this is equivalent to House Robber: pick n non-adjacent items
2
Handle Circularity
Split into two linear problems: with/without first element
3
Apply DP
Use 2D DP: dp[i][j] = max sum with j picks from first i elements
4
Combine Results
Return maximum of both linear solutions
Key Takeaway
๐ŸŽฏ Key Insight: Transform circular constraint problem into classic House Robber DP by handling first/last element circularity with two separate cases.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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