題目
愛麗絲有一串氣球排列在繩子上,這些氣球的顏色由一個以 0 為起始索引的字串 colors 表示,其中 colors[i] 代表第 ith 個氣球的顏色。
艾莉絲希望這條繩子色彩繽紛。她不希望有兩個連續的氣球顏色相同,因此向鮑伯求助。鮑伯可以移除繩子上的一些氣球來達到這個效果。你會得到一個以 0 為索引的整數陣列 neededTime ,其中 neededTime[i] 代表鮑伯需要移除繩子上第 ith 個氣球所花費的時間(以秒為單位)。
回傳鮑伯需要讓這條繩子變得五彩繽紛所需的最少時間。
我的練習
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
sum_time = 0
for i in range(len(colors) - 1):
if colors[i] == colors[i + 1]:
sum_time += min(neededTime[i], neededTime[i + 1])
neededTime[i + 1] = max(neededTime[i], neededTime[i + 1])
return sum_time
func minCost(colors string, neededTime []int) int {
sum := 0
for i := 0; i < len(colors)-1; i++ {
if colors[i] == colors[i+1] {
sum += min(neededTime[i], neededTime[i+1])
neededTime[i+1] = max(neededTime[i], neededTime[i+1])
}
}
return sum
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
impl Solution {
pub fn min_cost(colors: String, mut needed_time: Vec<i32>) -> i32 {
let mut sum = 0;
let colors_bytes = colors.as_bytes();
for i in 0..colors.len() - 1 {
if colors_bytes[i] == colors_bytes[i + 1] {
sum += needed_time[i].min(needed_time[i + 1]);
needed_time[i + 1] = needed_time[i].max(needed_time[i + 1]);
}
}
sum
}
}