Eat Pizzas! - Problem

You are given an integer array pizzas of size n, where pizzas[i] represents the weight of the i-th pizza.

Every day, you eat exactly 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights W, X, Y, and Z, where W ≤ X ≤ Y ≤ Z, you gain the weight of only 1 pizza!

On odd-numbered days (1-indexed), you gain a weight of Z (the heaviest pizza).

On even-numbered days, you gain a weight of Y (the second heaviest pizza).

Find the maximum total weight you can gain by eating all pizzas optimally.

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

Input & Output

Example 1 — Single Day
$ Input: pizzas = [3, 1, 4, 2]
Output: 4
💡 Note: We have 4 pizzas, so exactly 1 day of eating. Day 1 is odd, so we gain the weight of the heaviest pizza. Sorting [3,1,4,2] gives [1,2,3,4], so we gain weight 4.
Example 2 — Multiple Days
$ Input: pizzas = [10, 8, 7, 6, 5, 4, 3, 2]
Output: 25
💡 Note: We have 8 pizzas = 2 days. Day 1 (odd): gain heaviest from group = 10. Day 2 (even): gain second heaviest from group = 8. Optimal grouping gives us 10 + 8 + 7 = 25.
Example 3 — Equal Weights
$ Input: pizzas = [5, 5, 5, 5]
Output: 5
💡 Note: All pizzas have equal weight. Day 1 (odd): any grouping will have Z = 5, so we gain 5. Total weight gained is 5.

Constraints

  • 4 ≤ pizzas.length ≤ 1000
  • pizzas.length is a multiple of 4
  • 1 ≤ pizzas[i] ≤ 1000

Visualization

Tap to expand
Eat Pizzas! - Greedy Sorting Approach INPUT Pizza Weights Array: 3 i=0 1 i=1 4 i=2 2 i=3 W=3 X=1 n = 4 (multiple of 4) Days = n/4 = 1 day pizzas = [3, 1, 4, 2] Day 1 (odd): gain Z (heaviest) Day 2 (even): gain Y (2nd heaviest) Eat 4 pizzas per day ALGORITHM STEPS 1 Sort Descending [4, 3, 2, 1] 4 3 2 1 2 Count Days total_days = 4/4 = 1 odd_days = 1, even_days = 0 3 Assign Pizzas Odd days: take heaviest (Z) Even days: take 2nd (Y) Day 1 (odd): Eat [1,2,3,4] --> Gain 4 4 Sum Weights Total = 4 (from day 1) result = 4 FINAL RESULT Optimal Eating Strategy: Day 1 (Odd Day) Eat: W=1, X=2, Y=3, Z=4 Gain: Z = 4 Heaviest Pizza Weight: 4 Maximum Weight Gained: 4 Status: OK Output matches: 4 Key Insight: Sort pizzas in descending order. For odd days, pick the heaviest (Z) pizza from each group of 4. For even days, pick the second heaviest (Y). This greedy approach maximizes total weight gained because we always prioritize getting the largest possible values on each day type. TutorialsPoint - Eat Pizzas! | Greedy Sorting Approach
Asked in
Google 42 Meta 38 Amazon 35 Microsoft 28
23.4K Views
Medium Frequency
~15 min Avg. Time
847 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