Created
November 3, 2025 17:24
-
-
Save tatsuyax25/022f80baa1b43edfeb70a7beaa26bb5b to your computer and use it in GitHub Desktop.
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 Bo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Removes balloons to ensure no two adjacent balloons have the same color, | |
| * minimizing the total removal time. | |
| * | |
| * @param {string} colors - A string where each character represents a balloon's color. | |
| * @param {number[]} neededTime - An array where each element is the time to remove the corresponding balloon. | |
| * @return {number} - The minimum total time to remove balloons to satisfy the condition. | |
| */ | |
| var minCost = function(colors, neededTime) { | |
| let totalTime = 0; // Total time to remove balloons | |
| let maxTimeInGroup = 0; // Max time in the current group of same-colored balloons | |
| for (let i = 0; i < colors.length; i++) { | |
| if (i > 0 && colors[i] !== colors[i - 1]) { | |
| // New color group starts, reset maxTimeInGroup | |
| maxTimeInGroup = 0; | |
| } | |
| // Add current time to total | |
| totalTime += neededTime[i]; | |
| // Track the max time in the current group | |
| maxTimeInGroup = Math.max(maxTimeInGroup, neededTime[i]); | |
| // If it's the end of a group, subtract the max time (we keep that balloon) | |
| if (i === colors.length - 1 || colors[i] !== colors[i + 1]) { | |
| totalTime -= maxTimeInGroup; | |
| } | |
| } | |
| return totalTime; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment