1578. Minimum Time to Make Rope Colorful

First though...linear scan and using min heap

T: O(n*nlogn)

```java
class Solution {
    public int minCost(String colors, int[] neededTime) {
        char pre = colors.charAt(0);
        int i = 1;
        int result = 0;
        Queue<Integer> minHeap = new PriorityQueue<>();
        while (i < colors.length()) {
            if (colors.charAt(i) == pre) {
                minHeap.offer(neededTime[i-1]);
                while (i < colors.length() && colors.charAt(i) == pre) {
                    minHeap.add(neededTime[i]);
                    i++;
                }
                while (!minHeap.isEmpty() && minHeap.size() > 1) {
                    System.put.println(minHeap.get())
                    result += minHeap.poll();
                }
                pre = colors.charAt(i-1);
            } else {
                i++;
                pre = colors.charAt(i-1);
            }
        }
        return result;
    }
}

/***
if same -> remove and add these all same to pq
if not same -> step2: pop pq until one (min heap), add these pop time to result
end aslo step2
 */
```

actually can use 2 pointers

utilize every group's max and total

we can find ans is = total - max

more fast, we can only one pass

we only add smaller number to result, how to do it?

maintain a max value for each round, then we can only can smaller one to result (when change group, just reset it's to new group init max)

Last updated

Was this helpful?