-
[Leetcode] 1578. Minimum Time to Make Rope Colorful - Swift 1차 시도 (탈락)Algorithm 2022. 12. 30. 20:51
https://leetcode.com/problems/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.
// testcases and explanation 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. 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. Input: colors = "aabaa", neededTime = [1,2,3,4,1] Output: 2 Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. // 탈락한 케이스 Input: colors = "aaabbbabbbb", neededTime = [3,5,10,7,5,3,5,5,4,8,1] Output: 25 Expected: 26 // 원인 나의 로직은 2번 반복하는 케이스에 대해서만 예외 처리를 해주고 있지만 그 이상 반복되는 케이스에 대해서는 처리해주고 있지 않다.
func minCost(_ colors: String, _ neededTime: [Int]) -> Int { var sum = 0 var previousColor = "" var previousCost = 0 let zipped = zip(colors, neededTime) for i in zipped { if previousColor == String(i.0) { let cost = min(previousCost, i.1) sum += cost } previousColor = String(i.0) previousCost = i.1 } return sum }
'Algorithm' 카테고리의 다른 글
[Programmers] 나머지 한 점 - Swift (통과) (0) 2022.12.31 [Leetcode] 1375. Number of Times Binary String Is Prefix-Aligned - Swift (통과) (0) 2022.12.30 [백준] (Swift) 1697번: 숨바꼭질 - BFS 문제 (0) 2022.05.09 [Programmers] 정렬 : 가장 큰 수 (0) 2022.01.27 [Programmers] 정렬 : K번째수 (0) 2022.01.27