Problem

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.

Examples

Example 1:

1
2
3
4
5
6
7
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:

1
2
3
4
5
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:

1
2
3
4
5
6
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.

Solution

Method 1 - Greedy

Here is the approach:

  1. In any sequence of consecutive identical characters, all but one must be removed.
  2. To minimize the total time, always delete the balloon with the lower removal cost in each pair of duplicates.
  3. For each such group, add the minimum of the two adjacent costs to the answer.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
	public int minCost(String colors, int[] neededTime) {
		int ans = 0;
		for(int i = 1; i < colors.length; i++) {
			if (colors.charAt(i) == colors.charAt(i-1)) {
				ans = ans + Math.min(neededTime[i], neededTime[i-1]);
				neededTime[i] = Math.max(neededTime[i], neededTime[i-1]);
			}
		}
		return ans;
	}
}

Complexity

  • ⏰ Time complexity: O(n). We iterate through the string once, comparing each character with the previous one and updating the answer in constant time per step.
  • 🧺 Space complexity: O(1). Only a few variables are used for tracking the answer and updating the neededTime array; no extra space is required proportional to the input size.