Leetcode PHP题解–D127 455. Assign Cookies

Time:2022-9-21

D127 455. Assign Cookies

topic link

455. Assign Cookies

topic analysis

Given two arrays, the first array represents the capacity of each container, and the second array represents the number of each item. The items need to be stuffed into the container, but there are two conditions.

Condition 1: Only one item can be stuffed in a container;

Condition 2: An item can only be stuffed into one container, but not all.

For example, when the size of the container is 1 and the number of items is 3, the item can be stuffed into this container, but the remaining 2 items cannot be taken and stuffed into other containers.

Fill as many containers as possible and return the number of filled containers.

Problem solving ideas

At first, I didn't notice that this condition could not be filled, so I went back directly to calculate the number of intersection elements.

First, in order to fill as much as possible and reduce waste, the two arrays need to be sorted in descending order. Otherwise, there will be many voids in the container.

Next, it's time to start distributing items. Because the allocated items can have leftovers, we start from the item quantity array. If the current item quantity is greater than or equal to the current container capacity, it is allocated to it. If it is less than that, it means that the container can no longer be stuffed with items. Once the allocation is successful, directly start to allocate the next item.

final code

<?php

class Solution {

    /**
     * @param Integer[] $g
     * @param Integer[] $s
     * @return Integer
     */
    function findContentChildren($g, $s) {
        $total = 0;
        foreach($s as $key => $value){
            while( !is_null(key($g)) ){
                if (current($g)<=$value ){
                    $total++;
                    next($g);
                    break;
                }
                next($g);
            }
        }
        return $total;
    }
}

If you think this article is useful to you, you are welcome to use Love Power to fund it.

Recommended Today

PromiseA+ specification

PromiseA+ specification the term A promise is an object or function with a then method, and its behavior follows the PromiseA+ specification thenable is an object or function with a then method value is the value when the Promise state is successful, and is also the parameter of resolve, including various data types, undefined / […]