LeetCode-in-Java

3457. Eat Pizzas!

Medium

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!

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:

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:

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

Constraints:

Solution

class Solution {
    public long maxWeight(int[] pizzas) {
        int max = 0;
        for (int x : pizzas) {
            max = Math.max(max, x);
        }
        int[] count = new int[max + 1];
        for (int x : pizzas) {
            count[x]++;
        }
        int m = pizzas.length;
        int n = m / 4;
        int index = 0;
        for (int x = max; x > 0; --x) {
            if (count[x] != 0) {
                int c = count[x];
                while (c-- > 0) {
                    pizzas[index++] = x;
                }
                if (index >= m / 2) {
                    break;
                }
            }
        }
        long ans = 0;
        for (int i = 0; i < (n + 1) / 2; ++i) {
            ans += pizzas[i];
        }
        int k = n - (n + 1) / 2;
        for (int i = (n + 1) / 2 + 1; k > 0; i += 2, k--) {
            ans += pizzas[i];
        }
        return ans;
    }
}