Taro Logo

Eat Pizzas!

#77 Most AskedMedium
0 views
Topics:
ArraysGreedy Algorithms

You are given an integer array pizzas of size n, where pizzas[i] represents the weight of the ith 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.
  • On even-numbered days, you gain a weight of Y.

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.

Example 1:

Input: pizzas = [1,2,3,4,5,6,7,8]

Output: 14

Explanation:

  • On day 1, you eat pizzas at indices [1, 2, 4, 7] = [2, 3, 5, 8]. You gain a weight of 8.
  • On day 2, you eat pizzas at indices [0, 3, 5, 6] = [1, 4, 6, 7]. You gain a weight of 6.

The total weight gained after eating all the pizzas is 8 + 6 = 14.

Example 2:

Input: pizzas = [2,1,1,1,1,1,1,1]

Output: 3

Explanation:

  • On day 1, you eat pizzas at indices [4, 5, 6, 0] = [1, 1, 1, 2]. You gain a weight of 2.
  • On day 2, you eat pizzas at indices [1, 2, 3, 7] = [1, 1, 1, 1]. You gain a weight of 1.

The total weight gained after eating all the pizzas is 2 + 1 = 3.

Constraints:

  • 4 <= n == pizzas.length <= 2 * 105
  • 1 <= pizzas[i] <= 105
  • n is a multiple of 4.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the exact definition and length of the 'days' or the alternating maximum pattern over the days mentioned in the problem?
  2. Are the weights of the pizzas guaranteed to be positive integers, or can they include zeros or negative values?
  3. What is the exact size range of the input array, and is the total number of pizzas guaranteed to be a multiple of 4?
  4. If multiple combinations of eating pizzas yield the same total maximum weight, does any valid grouping suffice, or is a specific configuration expected?
  5. What should be returned if the input array is empty or has fewer than 4 pizzas?

Brute Force Solution

Approach

To maximize the total gained weight, we should distribute the heaviest pizzas to the positions where their weights contribute to the answer. There are total days equal to the number of pizzas divided by four, where odd days contribute the maximum pizza of a group of four and even days contribute the second maximum. By sorting the array, we can greedily assign the absolute largest pizzas to the odd days, and then for even days, pair the remaining largest pizzas such that we collect the second largest from each pair.

Here's how the algorithm would work step-by-step:

  1. Sort the pizzas array in ascending order to access the heaviest pizzas at the end.
  2. Calculate the total number of days, the number of odd-numbered days, and the number of even-numbered days.
  3. Greedily select the largest elements from the back of the sorted array for each odd-numbered day.
  4. For each even-numbered day, skip the largest remaining pizza and add the second-largest remaining pizza to the total weight.
  5. Return the accumulated total weight.

Code Implementation

def max_weight(pizzas: list[int]) -> int:
    # Sort the pizzas in ascending order to easily access largest elements
    pizzas.sort()
    total_days = len(pizzas) // 4
    odd_days = (total_days + 1) // 2
    even_days = total_days // 2
    total_weight = 0
    index = len(pizzas) - 1
    # Pick the largest available pizzas for all odd-numbered days
    for _ in range(odd_days):
        total_weight += pizzas[index]
        index -= 1
    # For even-numbered days, take the second largest in each pair of large pizzas
    for _ in range(even_days):
        index -= 1
        total_weight += pizzas[index]
        index -= 1
    return total_weight

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of n pizzas takes O(n log n) time, and the subsequent linear scan over the largest elements takes O(n) time.
Space Complexity
O(1) – In Python, sorting can be done in-place with Timsort which uses O(n) extra space in the worst case, but auxiliary space beyond the sorting buffer is O(1).

Optimal Solution

Approach

To maximize the total weight gained, we should sort the pizzas in ascending order and greedily pick the largest possible pizzas. There are n / 4 days in total, divided into odd days and even days. For each odd day, we can gain the largest available pizza weight, whereas for each even day, we gain the second largest pizza weight from a group.

Here's how the algorithm would work step-by-step:

  1. Sort the pizza array in non-decreasing order.
  2. Calculate the total number of days as n divided by 4, and partition them into odd-numbered and even-numbered days.
  3. Greedily select the largest elements from the end of the array for all odd-numbered days.
  4. For each even-numbered day, skip one pizza to serve as the largest in its four-pizza group and take the second largest.
  5. Return the accumulated sum of the selected pizza weights.

Code Implementation

def max_weight_gain(pizzas: list[int]) -> int:
    # Sort the pizzas in ascending order to easily access the largest elements
    pizzas.sort()
    total_days = len(pizzas) // 4
    odd_days = (total_days + 1) // 2
    even_days = total_days // 2
    total_weight = 0
    index = len(pizzas) - 1
    # Take the largest available pizza for each odd day
    for day_step in range(odd_days):
        total_weight += pizzas[index]
        index -= 1
    # Take the second largest available pizza for each even day
    for day_step in range(even_days):
        total_weight += pizzas[index - 1]
        index -= 2
    return total_weight

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of size n takes O(n log n) time, and then we perform a single linear scan from the end of the array taking O(n) time.
Space Complexity
O(1) – In-place sorting uses O(1) or O(log n) auxiliary space depending on the sorting algorithm, without requiring any additional data structures.

Edge Cases

Input array has fewer than 4 elements or an invalid length not divisible by 4
How to Handle:
Return zero or handle as an invalid input since exactly four pizzas must be eaten each day.
Maximum possible input constraints leading to integer overflow during weight summation
How to Handle:
Use 64-bit integer types like long in Java or standard integers in Python to accumulate the total weight safely.
All pizza weights in the array are identical
How to Handle:
Sorting the array allows the greedy choice logic to group identical elements correctly without failing.
Extremely large input arrays of size up to 10 to the 5th power
How to Handle:
Implement an O(N log N) sorting-based greedy approach to ensure the solution executes well within time limits.
Pizza weights containing zero or negative values
How to Handle:
The greedy selection logic remains mathematically sound because sorting still isolates the largest available weights correctly.
Number of days is odd versus even leading to different alternating max selection counts
How to Handle:
Carefully partition the total days into ceil(days/2) odd days and floor(days/2) even days to pick second-maximums and maximums respectively.
0/257 completed