-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximumScoreFromRemovingSubstrings1717.java
78 lines (69 loc) · 2.5 KB
/
MaximumScoreFromRemovingSubstrings1717.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
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
public class MaximumScoreFromRemovingSubstrings1717 {
/*You are given a string s and two integers x and y. You can perform two types of operations any number of times.
Remove substring "ab" and gain x points.
For example, when removing "ab" from "cabxbae" it becomes "cxbae".
Remove substring "ba" and gain y points.
For example, when removing "ba" from "cabxbae" it becomes "cabxe".
Return the maximum points you can gain after applying the above operations on s.
*/
class Solution {
public int maximumGain(String s, int x, int y) {
int score = 0 ;
String high= x>y ? "ab" : "ba" ;
String low = high.equals("ba") ? "ab" : "ba" ;
String first = removeSub(s, high);
int cnt = (s.length() - first.length()) /2;
score += cnt * Math.max(x, y);
String second = removeSub(first, low);
cnt = (first.length() - second.length()) /2;
score += cnt * Math.min(x, y);
return score ;
}
private String removeSub(String s , String target){
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++){
char curr = s.charAt(i);
if ( curr == (target.charAt(1)) && !stack.isEmpty() && stack.peek()==(target.charAt(0))){
stack.pop() ;
}
else stack.push(curr);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
//optimal solution: -
class optimalSolution {
public int maximumGain(String s, int x, int y) {
if (x < y) {
int temp = x;
x = y;
y = temp;
s = new StringBuilder(s).reverse().toString();
}
int aCount = 0, bCount = 0, totalPoints = 0;
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (currentChar == 'a') {
aCount++;
} else if (currentChar == 'b') {
if (aCount > 0) {
aCount--;
totalPoints += x;
} else {
bCount++;
}
} else {
totalPoints += Math.min(bCount, aCount) * y;
aCount = bCount = 0;
}
}
totalPoints += Math.min(bCount, aCount) * y;
return totalPoints;
}
}
}