-
Notifications
You must be signed in to change notification settings - Fork 2
/
MinimumDeletionCostToAvoidRepeatingLetters.java
67 lines (60 loc) · 1.88 KB
/
MinimumDeletionCostToAvoidRepeatingLetters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package Leetcode;
/**
* @author kalpak
*
* 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.
*
* Example 1:
* 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).
*
*
* Example 2:
* 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.
*
*
* Example 3:
* Input: s = "aabaa", cost = [1,2,3,4,1]
* Output: 2
* Explanation: Delete the first and the last character, getting the string ("aba").
*
*
* Constraints:
*
* s.length == cost.length
* 1 <= s.length, cost.length <= 10^5
* 1 <= cost[i] <= 10^4
* s contains only lowercase English letters.
*
*/
public class MinimumDeletionCostToAvoidRepeatingLetters {
public static int minCost(String s, int[] cost) {
int result = 0;
int runningSum = 0;
int runningMax = 0;
for(int i = 0; i < s.length(); i++) {
if(i > 0 && s.charAt(i) != s.charAt(i - 1)) {
result += runningSum - runningMax;
runningSum = 0;
runningMax = 0;
}
runningSum += cost[i];
runningMax = Math.max(runningMax, cost[i]);
}
result += runningSum - runningMax;
return result;
}
public static void main(String[] args) {
String s = "aabaa";
int[] cost = new int[]{1, 2, 3, 4, 1};
System.out.println(minCost(s, cost));
}
}