난이도: Easy
Problem 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.
Problem Example
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
✏️ Solution
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
n = len(blocks)
answer = n+1
for i in range(n-k+1):
answer = min(answer, blocks[i:i+k].count('W'))
if answer == 0:
return 0
return answer
blocks에서 k의 길이를 갖는 substring에서 'W' 갯수를 세고 그 갯수가 제일 작은 값이 답이 된다.
예를 들어 blocks는 "WBBWWBBWBW"이고 k=7이라면, 아래 그림과 같이 구할 수 있다.
⚙️ Runtime & Memory
문제: 2379. Minimum Recolors to Get K Consecutive Black Blocks
깃허브: github
algorithmPractice/LeetCode/2463-minimum-recolors-to-get-k-consecutive-black-blocks at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1358. Number of Substrings Containing All Three Characters (Python) (0) | 2025.03.11 |
---|---|
[LeetCode] 3208. Alternating Groups II (Python) (0) | 2025.03.09 |
[LeetCode] 2523. Closest Prime Numbers in Range (Python) (0) | 2025.03.07 |
[LeetCode] 2965. Find Missing and Repeated Values (Python) (0) | 2025.03.06 |
[LeetCode] 2579. Count Total Number of Colored Cells (Python) (0) | 2025.03.05 |