Skip to content

2209. Minimum White Tiles After Covering With Carpets

Difficulty Topics

Description

You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:

  • floor[i] = '0' denotes that the ith tile of the floor is colored black.
  • On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.

You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.

Return the minimum number of white tiles still visible.

 

Example 1:

Input: floor = "10110101", numCarpets = 2, carpetLen = 2
Output: 2
Explanation: 
The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.
No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.

Example 2:

Input: floor = "11111", numCarpets = 2, carpetLen = 3
Output: 0
Explanation: 
The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.
Note that the carpets are able to overlap one another.

 

Constraints:

  • 1 <= carpetLen <= floor.length <= 1000
  • floor[i] is either '0' or '1'.
  • 1 <= numCarpets <= 1000

Solution

minimum-white-tiles-after-covering-with-carpets.py
class Solution:
    def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:
        n = len(floor)
        total = 0
        prefix = [0]

        if numCarpets * carpetLen >= n: return 0

        for x in floor:
            if x == "1": total += 1
            prefix.append(prefix[-1] + int(x == "1"))

        if total == 0: return 0

        @cache
        def go(index, carpets):
            if index == n: return 0

            res = float('-inf')
            res = max(res, go(index + 1, carpets))

            bound = min(n, index + carpetLen)
            if carpets > 0 and prefix[bound] - prefix[index] > 0:
                res = max(res, go(bound, carpets - 1) + prefix[bound] - prefix[index])

            return res

        res = go(0, numCarpets)

        return total - res if total - res > 0 else 0