carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2379: Minimum Recolors to Get K Consecutive Black Blocks #389

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors 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 recolor a white block such that it becomes a black block.

Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.

Example 1:

Input: blocks = "WBBWWBBWBW", k = 7 Output: 3 Explanation: One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks so that blocks = "BBBBBBBWBW". It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations. Therefore, we return 3.

Example 2:

Input: blocks = "WBWBBBW", k = 2 Output: 0 Explanation: No changes need to be made, since 2 consecutive black blocks already exist. Therefore, we return 0.

Constraints:

n == blocks.length 1 <= n <= 100 blocks[i] is either 'W' or 'B'. 1 <= k <= n

carloscn commented 11 months ago

Analysis

static int32_t minimum_recolors(const char *blocks, size_t k)
{
    int32_t ret = 0;
    size_t len;

    UTILS_CHECK_PTR(blocks);
    UTILS_CHECK_LEN(len = strlen(blocks));
    UTILS_CHECK_CONDITION(len < k, ret, "len < k");

    size_t max_white = 0, max_black = 0;
    for (size_t i = 0; i < len - k; i ++) {
        size_t count_white = 0, count_black = 0;
        for (size_t j = 0; j < k; j ++) {
            if (blocks[j + i] == 'W') {
                count_white ++;
            } else if  (blocks[j + i] == 'B') {
                count_black ++;
            } else {
                ret = -1;
                return ret;
            }
        }
        max_white = UTILS_MAX(max_white, count_white);
        max_black = UTILS_MAX(max_black, count_black);
        if (max_white >= k || max_black >= k) {
            max_white = 0;
            max_black = 0;
        }
    }

    ret = UTILS_MIN(max_white, max_black);

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170892 https://github.com/carloscn/structstudy/commit/b82cbdf716536e04a5539ff7e17b5c7930555baf