[LeetCode] Minimum White Tiles After Covering With Carpets

2209. Minimum White Tiles After Covering With Carpets

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int dp[1001][1001];
int w[1002];
int helper(string& f, int p, int left, int& len) {
if(p >= f.length()) return 0;
if(left == 0) return w[p];
if(dp[p][left] != -1) return dp[p][left];
dp[p][left] = helper(f, p + 1, left, len) + (f[p] == '1');
if(f[p] == '1') {
dp[p][left] = min(dp[p][left], helper(f, p + len, left - 1, len));
}
return dp[p][left];
}
public:
int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {
memset(dp,-1,sizeof(dp));
memset(w, 0,sizeof(w));
for(int i = floor.length(); i >= 0; i--) {
w[i] += w[i+1];
if(floor[i] == '1') w[i]++;
}
return helper(floor, 0, numCarpets, carpetLen);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/minimum-white-tiles-after-covering-with-carpets/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.