Minimum Time to Make Rope Colorful

medium array string dp greedy

Problem

colors[i] is the i-th balloon's color, neededTime[i] its removal cost. Return the minimum total time to remove balloons so no two consecutive have the same color.

Inputcolors="abaac", neededTime=[1,2,3,4,5]
Output3
Run "aa" at indices 2,3 → remove the 3-cost one, keep the 4-cost.

def min_cost(colors, neededTime):
    ans = i = 0; n = len(colors)
    while i < n:
        j = i; total = mx = 0
        while j < n and colors[j] == colors[i]:
            total += neededTime[j]; mx = max(mx, neededTime[j]); j += 1
        ans += total - mx; i = j
    return ans
function minCost(colors, neededTime) {
  let ans = 0, i = 0, n = colors.length;
  while (i < n) {
    let j = i, total = 0, mx = 0;
    while (j < n && colors[j] === colors[i]) { total += neededTime[j]; if (neededTime[j] > mx) mx = neededTime[j]; j++; }
    ans += total - mx; i = j;
  }
  return ans;
}
class Solution {
    public int minCost(String colors, int[] neededTime) {
        int ans = 0, i = 0, n = colors.length();
        while (i < n) {
            int j = i, total = 0, mx = 0;
            while (j < n && colors.charAt(j) == colors.charAt(i)) { total += neededTime[j]; mx = Math.max(mx, neededTime[j]); j++; }
            ans += total - mx; i = j;
        }
        return ans;
    }
}
int minCost(string colors, vector& neededTime) {
    int ans = 0, i = 0, n = colors.size();
    while (i < n) {
        int j = i, total = 0, mx = 0;
        while (j < n && colors[j] == colors[i]) { total += neededTime[j]; mx = max(mx, neededTime[j]); j++; }
        ans += total - mx; i = j;
    }
    return ans;
}
Time: O(n) Space: O(1)