-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum Time to Make-Rope-Colorful.java
More file actions
40 lines (32 loc) · 1.76 KB
/
Copy pathMinimum Time to Make-Rope-Colorful.java
File metadata and controls
40 lines (32 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
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.
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.
*/
import java.util.Arrays;
public class Solution {
public int minCost(String colors, int[] neededTime) {
int n = colors.length();
int[] dp = new int[n];
Arrays.fill(dp, -1);
return calculateMinCost(n - 1, colors, neededTime, dp, 'A', neededTime[n - 1]);
}
private int calculateMinCost(int i, String colorSequence, int[] timeRequired, int[] memo, char previousColor, int previousTime) {
if (i < 0) {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
if (colorSequence.charAt(i) == previousColor) {
return memo[i] = calculateMinCost(i - 1, colorSequence, timeRequired, memo, colorSequence.charAt(i), Math.max(timeRequired[i], previousTime)) + Math.min(timeRequired[i], previousTime);
} else {
return memo[i] = calculateMinCost(i - 1, colorSequence, timeRequired, memo, colorSequence.charAt(i), timeRequired[i]);
}
}
}