2025-08-06 13:17:09 +0000 UTC

Fruits Into Baskets III

Code

class Solution:
    def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
        length = len(baskets)
        section_length = int(math.sqrt(length))
        sections = (length + section_length - 1) // section_length
        count = 0
        sections_max = [0] * sections
        for i in range(length):
            section = i // section_length
            sections_max[section] = max(sections_max[section], baskets[i])
        for fruit in fruits:
            unset = 1
            for section in range(sections):
                if sections_max[section] < fruit:
                    continue
                choose = 0
                sections_max[section] = 0
                for i in range(section_length):
                    pos = section * section_length + i
                    if pos < length and baskets[pos] >= fruit and not choose:
                        baskets[pos] = 0
                        choose = 1
                    if pos < length:
                        sections_max[section] = max(sections_max[section], baskets[pos])
                unset = 0
                break
            count += unset
        return count