↓Skip to main content
  1. LeetCode/

LeetCode 3074: Apple Redistribution into Boxes

·1 min· ·
LeetCode Easy Array Greedy Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2024-03-10

  • Submissions: Accepted (first try)

Approach
#

A pack may be split across boxes, so only total capacity matters. To use the fewest boxes, take the largest first (Greedy Template 1) and stop once the accumulated capacity reaches the apple total.

My Attempts
#

Passed on the first try during the 2024 contest by sorting and accumulating from the largest.

Solution
#

class Solution:
    def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
        need = sum(apple)
        for i, c in enumerate(sorted(capacity, reverse=True), 1):
            need -= c
            if need <= 0:
                return i
        return len(capacity)

Complexity
#

Time O(m log m), space O(m).

Mistakes to Avoid
#

  • Apples can be split, so only the total matters.

Interview Explanation
#

Since apples can be split, only total capacity matters; I sort boxes by capacity descending and take them until the capacity covers every apple. Time O(m log m).

Related

LeetCode 2335: Minimum Amount of Time to Fill Cups
·1 min
LeetCode Easy Array Greedy Sorting Heap-Priority-Queue
LeetCode 2335 note: the answer is max(the largest count, ceil(total / 2)); simulating means filling one cup from each of the two largest every second
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 1005 note: negate the smallest value each time; once the smallest is positive, only the parity of the remaining count matters
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 3075: Maximize Happiness of Selected Children
·1 min
LeetCode Medium Array Greedy Sorting
LeetCode 3075 note: choose k children from the happiest, where the i-th choice loses i, floored at 0