Teaching Kids Programming – Redistribute Items to Boxes (Knapsack Problem, Binary Search Algorithm)


Teaching Kids Programming: Videos on Data Structures and Algorithms

Apple Redistribution into Boxes

You are given an array apple of size n and an array capacity of size m.

There are n packs where the ith pack contains apple[i] apples. There are m boxes as well, and the ith box has a capacity of capacity[i] apples.

Return the minimum number of boxes you need to select to redistribute these n packs of apples into boxes.

Note that, apples from the same pack can be distributed into different boxes.

Example 1:
Input: apple = [1,3,2], capacity = [4,3,1,5,2]
Output: 2
Explanation: We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.

Example 2:
Input: apple = [5,5,5], capacity = [2,4,2,7]
Output: 4
Explanation: We will need to use all the boxes.

Constraints:
1 <= n == apple.length <= 50
1 <= m == capacity.length <= 50
1 <= apple[i], capacity[i] <= 50
The input is generated such that it’s possible to redistribute packs of apples into boxes.

Redistribute Items to Boxes (Knapsack Problem, Binary Search Algorithm)

Previously: Teaching Kids Programming – Greedy Algorithm to Redistribute Items to Boxes (Knapsack Problem), we adopt the greedy algorithm to pack items into the box which has a larger capacity.

We can optimize this bit by computing the prefix sum (accumulated), so we can find out the insert position which corresponds to the number of boxes required. We can binary search it since the prefix sum is sorted.

1
2
3
4
5
6
7
8
class Solution:
    def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
        x = sum(apple)
        if x > sum(capacity):
            return -1        
        capacity.sort(reverse=True)
        arr = list(accumulate(capacity))
        return bisect_left(arr, x) + 1
class Solution:
    def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
        x = sum(apple)
        if x > sum(capacity):
            return -1        
        capacity.sort(reverse=True)
        arr = list(accumulate(capacity))
        return bisect_left(arr, x) + 1

The time complexity of overall solution is still the same, but the searching bit will be O(LogM) instead of O(M).

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
468 words
Last Post: Beware of the Malicious Transactions on TRON Blockchain
Next Post: Two Windows Tips: Turn Off Delivery Optimization and Tweak Privacy Settings

The Permanent URL is: Teaching Kids Programming – Redistribute Items to Boxes (Knapsack Problem, Binary Search Algorithm)

Leave a Reply