the third one in Weekly Contest 205.
Difficulty : Medium
Related Topics : Greedy
Given a string
s
and an array of integerscost
wherecost[i]
is the cost of deleting the ith character ins
.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.
Input: s = "abaac", cost = [1,2,3,4,5] Output: 3 Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other).
Input: s = "abc", cost = [1,2,3] Output: 0 Explanation: You don't need to delete any character because there are no identical letters next to each other.
Input: s = "aabaa", cost = [1,2,3,4,1] Output: 2 Explanation: Delete the first and the last character, getting the string ("aba").
s.length == cost.length
1 <= s.length, cost.length <= 10^5
1 <= cost[i] <= 10^4
s
contains only lowercase English letters.
- mine
- Java
Runtime: 4 ms, faster than 100.00%, Memory Usage: 48.4 MB, less than 96.97% of Java online submissions
// O(N)time // O(N)space public int minCost(String s, int[] cost) { char[] arr = s.toCharArray(); int res = 0; int index = 0; for(int i = 1; i < arr.length; i++){ if(arr[i] == arr[index]){ if(cost[index] > cost[i]){ res += cost[i]; }else{ res += cost[index]; index = i; } }else{ index = i; } } return res; }
- Java