diff options
author | Jack Sangdahl <[email protected]> | 2025-03-07 19:53:48 -0700 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-07 19:53:48 -0700 |
commit | 3148809e3af8febf1f684933da6f71f7af5fd2e6 (patch) | |
tree | 3d19cf63dd8faba1db8c046b19056ab6f0070538 /min_recolour_k_block.c | |
parent | 4802a9af9bbcf85f03605510ca7bd149128f5066 (diff) | |
download | leetcode-3148809e3af8febf1f684933da6f71f7af5fd2e6.tar.gz leetcode-3148809e3af8febf1f684933da6f71f7af5fd2e6.zip |
2379. minimum recolours to get k consecutive black blocks
Diffstat (limited to 'min_recolour_k_block.c')
-rw-r--r-- | min_recolour_k_block.c | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/min_recolour_k_block.c b/min_recolour_k_block.c new file mode 100644 index 0000000..253fad2 --- /dev/null +++ b/min_recolour_k_block.c @@ -0,0 +1,39 @@ +// 2379. Minimum Recolors to Get K Consecutive Black Blocks +#include "leetcode.h" + +/* + * you are given a 0-indexed string 'blocks' of length 'n' where 'blocks[i]' is + * either 'W' or 'B', representing the colour of the i'th block. the characters + * 'W' and 'B' denote the colours white and black, respectively. you are also + * given an integer 'k', which is the desired number of consecutive black + * blocks. in one operation, you can recolour a white block such that it becomes + * a black block. return the minimum number of operations needed such that there + * is at least one occurence of 'k' consecutive black blocks. + */ + +int minimumRecolors(char *blocks, int k) { + int n = strlen(blocks), min = INT_MAX, flips = 0, cnt = 0, i = 0; + for (int j = 0; j < n; ++j) { + if (blocks[j] == 'W') { + flips++; + cnt++; + } else if (blocks[j] == 'B') + cnt++; + if (cnt == k) { + min = fmin(min, flips); + if (blocks[i] == 'W') { + flips--; + cnt--; + } else + cnt--; + i++; + } + } + return min; +} + +int main() { + char *b1 = "WBBWWBBWBW", *b2 = "WBWBBBW"; + printf("%d\n", minimumRecolors(b1, 7)); // expect: 3 + printf("%d\n", minimumRecolors(b2, 2)); // expect: 0 +} |