Eat Pizzas! - Problem

๐Ÿ• Pizza Eating Challenge!

You're participating in a unique pizza eating contest! Given an array pizzas where pizzas[i] represents the weight of the i-th pizza, you must eat exactly 4 pizzas every day until all pizzas are consumed.

Here's the twist: due to your incredible metabolism, when you eat 4 pizzas with weights W โ‰ค X โ‰ค Y โ‰ค Z, you only gain weight from one pizza:

  • Odd-numbered days (1st, 3rd, 5th, ...): You gain weight equal to Z (heaviest pizza)
  • Even-numbered days (2nd, 4th, 6th, ...): You gain weight equal to Y (second heaviest pizza)

Goal: Arrange your pizza consumption optimally to maximize your total weight gain!

Note: It's guaranteed that n is a multiple of 4, and each pizza can only be eaten once.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 2, 3, 4]
โ€บ Output: 4
๐Ÿ’ก Note: We have 4 pizzas, so exactly 1 day. Day 1 is odd, so we gain weight of Z (maximum pizza). Sorting: [1,2,3,4], we gain weight 4.
example_2.py โ€” Two Days
$ Input: [8, 6, 4, 2, 7, 5, 3, 1]
โ€บ Output: 14
๐Ÿ’ก Note: 8 pizzas = 2 days. Day 1 (odd): gain Z, Day 2 (even): gain Y. Optimal assignment gives us 8 (heaviest for day 1) + 6 (second heaviest for day 2) = 14.
example_3.py โ€” Three Days
$ Input: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 12]
โ€บ Output: 29
๐Ÿ’ก Note: 12 pizzas = 3 days. Days 1,3 are odd (gain Z), Day 2 is even (gain Y). Sorted: [12,11,10,9,8,7,6,5,4,3,2,1]. We get 12+11 (for 2 odd days) + 10 (for 1 even day) = 33. Wait, let me recalculate: 2 odd days get the 2 heaviest pizzas (12,11), 1 even day gets the next heaviest (10). Total = 12+11+10 = 33.

Constraints

  • 4 โ‰ค n โ‰ค 105
  • n is a multiple of 4
  • 1 โ‰ค pizzas[i] โ‰ค 109
  • Each pizza can only be eaten once

Visualization

Tap to expand
๐Ÿ• Optimal Pizza Eating StrategyAvailable Pizzas (sorted by weight)12111098765Day 1 (Odd) - Score ZWโ‰คXYZ=1212Gain: 12Day 2 (Even) - Score YWโ‰คXY=11Z11Gain: 11Optimal Total Weight Gain12 + 11 = 23Strategy: Place heaviest pizzas in scoring positions!
Understanding the Visualization
1
Identify Resources
Count how many scoring positions you have: odd days need Z, even days need Y
2
Sort by Value
Arrange pizzas from heaviest to lightest to prioritize high-value assignments
3
Optimal Assignment
Place the heaviest pizzas in scoring positions to maximize total gain
Key Takeaway
๐ŸŽฏ Key Insight: By sorting pizzas in descending order and strategically assigning the heaviest ones to scoring positions (Z for odd days, Y for even days), we maximize our total weight gain with optimal O(n log n) time complexity.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
58.4K Views
Medium Frequency
~25 min Avg. Time
1.8K 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