[LeetCode] Minimum Deletion Cost to Avoid Repeating Letters

1578. Minimum Deletion Cost to Avoid Repeating Letters

Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s.

Return the minimum cost of deletions such that there are no two identical letters next to each other.

Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minCost(string s, vector<int>& cost) {
int res(0), mx(0);
for(int i = 1; i < s.length(); i++) {
if(s[i] == s[i - 1]) {
if(mx) res += min(mx, cost[i]);
else res += min(cost[i - 1], cost[i]), mx = max(cost[i], cost[i - 1]);
mx = max(cost[i], mx);
} else mx = 0;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/23/PS/LeetCode/minimum-deletion-cost-to-avoid-repeating-letters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.