#3457

Eat Pizzas!

Medium
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

In the optimal solution, we sort the pizzas and strategically select the largest weights based on the day. This allows us to maximize the weight gained efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the pizzas in ascending order.
  2. 2Step 2: Initialize total weight gained to 0.
  3. 3Step 3: Iterate through the pizzas, taking the largest pizza for odd days and the second largest for even days, while grouping them optimally.
solution.py13 lines
1# Full working Python code
2
3def maxWeight(pizzas):
4    pizzas.sort()
5    total_weight = 0
6    n = len(pizzas)
7    for day in range(n // 4):
8        if day % 2 == 0:
9            total_weight += pizzas[n - 1 - (day * 4)]  # Z
10        else:
11            total_weight += pizzas[n - 2 - (day * 4)]  # Y
12    return total_weight
13

Complexity note: The sorting step dominates the complexity, making it O(n log n), while the subsequent loop runs in linear time.

  • 1Always sort the array to easily access the largest weights.
  • 2Group pizzas optimally based on the day to maximize weight gain.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.