1578. Minimum Time to Make Rope Colorful
Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
앨리스는 로프에 n개의 풍선을 배열했습니다. 0-인덱스 문자열 colors가 주어지며, colors[i]는 i번째 풍선의 색상입니다.
앨리스는 로프가 다채롭기를 원합니다. 그녀는 두 개의 연속된 풍선이 같은 색상이 되는 것을 원하지 않으므로 밥에게 도움을 요청합니다. 밥은 로프에서 풍선을 몇 개 제거하여 다채롭게 만들 수 있습니다. 0-인덱스 정수 배열 neededTime이 주어지며, neededTime[i]는 밥이 로프에서 i번째 풍선을 제거하는 데 필요한 시간(초)입니다.
밥이 로프를 다채롭게 만드는 데 필요한 최소 시간을 반환합니다.
Example 1:
Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:
Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
- n == colors.length == neededTime.length
- 1 <= n <= 10^5
- 1 <= neededTime[i] <= 10^4
- colors contains only lowercase English letters.
코드 1
class Solution {
fun minCost(colors: String, neededTime: IntArray): Int {
var answer = 0
for (l in 0 until colors.lastIndex) {
if (colors[l] == colors[l + 1]) {
if (neededTime[l] < neededTime[l + 1]) {
answer += neededTime[l]
} else {
answer += neededTime[l + 1]
neededTime[l + 1] = neededTime[l]
}
}
}
return answer
}
}
코드 2
class Solution {
fun minCost(colors: String, neededTime: IntArray): Int {
var answer = 0
var l = 0
for (r in 1..colors.lastIndex) {
if (colors[l] == colors[r]) {
if (neededTime[l] < neededTime[r]) {
answer += neededTime[l]
l = r
} else {
answer += neededTime[r]
}
} else {
l = r
}
}
return answer
}
}
'LeetCode > Two Pointers' 카테고리의 다른 글
[LeetCode][Kotlin] 42. Trapping Rain Water (0) | 2024.10.21 |
---|---|
[LeetCode][Kotlin] 779. K-th Symbol in Grammar (0) | 2024.10.19 |
[LeetCode][Kotlin] 189. Rotate Array (0) | 2024.10.19 |