LeetCode 1578.
Tags: LeetCode
package lc_1578;
/**
* String ex = "bbbaaa";
* int[] time = new int[]{4,9,3,8,8,9};
* Solution sol = new Solution();
* System.out.println(sol.minCost(ex, time));
*/
public class Solution {
public int minCost(String colors, int[] neededTime) {
int last = 0, index = 0;
int time = 0;
last = colors.charAt(0);
for (int i=1; i<colors.length(); i++){
index = i;
while (index < colors.length() && (int)colors.charAt(index) == last){
index++;
}
if (index != i){
time += returnSegTotal(i-1, index-1, neededTime);
i = index - 1;
}
last = colors.charAt(i);
}
return time;
}
public int returnSegTotal(int from, int to, int[] neededTime){
int max = 0, total = 0;
for (int i=from; i<=to; i++){
total += neededTime[i];
if (max < neededTime[i]) max = neededTime[i];
}
return total - max;
}
}
Check out the description of this problem at LC 1578.