philosyang.com

3457. Eat Pizzas! | 1704

I think that I am good enough on greedy problems.

 1class Solution:
 2    def maxWeight(self, pizzas: List[int]) -> int:
 3        # intuition
 4        # greedy?
 5        # sort and only look at the larger half
 6        # day0: largest0
 7        # day1: largest2
 8        # day2: largest3
 9        # ...
10
11        # close but:
12        # for 3 (odd) days, we actually need the [-1], [-2], and [-4]
13        # rather than the [-1], [-3], [-4]
14
15        n = len(pizzas)
16        days = n // 4
17        odd_days, even_days = (days + 1) // 2, days // 2
18        pizzas.sort()
19        result = 0
20        idx = 0
21
22        for _ in range(odd_days):
23            idx -= 1
24            result += pizzas[idx]
25        for _ in range(even_days):
26            idx -= 2
27            result += pizzas[idx]
28
29        return result

#Array #Greedy #Sorting #Python