Skip to content

Commit af947de

Browse files
authored
Update Maximum Score From Removing Substrings.java
1 parent e343d89 commit af947de

File tree

1 file changed

+26
-20
lines changed

1 file changed

+26
-20
lines changed
Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,35 @@
11
class Solution {
22
public int maximumGain(String s, int x, int y) {
3-
int score = 0;
4-
String firstPass = removeSubstring(s, x > y ? "ab" : "ba");
5-
int removeCount = (s.length() - firstPass.length()) / 2;
6-
score += removeCount * Math.max(x, y);
7-
String secondPass = removeSubstring(firstPass, x > y ? "ba" : "ab");
8-
removeCount = (firstPass.length() - secondPass.length()) / 2;
9-
score += removeCount * Math.min(x, y);
10-
return score;
11-
}
12-
13-
private String removeSubstring(String s, String target) {
14-
Stack<Character> stack = new Stack<>();
3+
// Swap if x < y so we can follow a single iteration
4+
if (x < y) {
5+
int temp = x;
6+
x = y;
7+
y = temp;
8+
s = new StringBuilder(s).reverse().toString();
9+
}
10+
int countA = 0;
11+
int countB = 0;
12+
int total = 0;
1513
for (int i = 0; i < s.length(); i++) {
1614
char c = s.charAt(i);
17-
if (c == target.charAt(1) && !stack.isEmpty() && stack.peek() == target.charAt(0)) {
18-
stack.pop();
15+
if (c == 'a') {
16+
countA++;
17+
} else if (c == 'b') {
18+
// Make a pair to consume the excess 'a' count
19+
if (countA > 0) {
20+
countA--;
21+
total += x;
22+
} else {
23+
countB++;
24+
}
1925
} else {
20-
stack.push(c);
26+
// Consume any possible number of pairs & reset the counter
27+
total += Math.min(countA, countB) * y;
28+
countA = 0;
29+
countB = 0;
2130
}
2231
}
23-
StringBuilder sb = new StringBuilder();
24-
while (!stack.isEmpty()) {
25-
sb.append(stack.pop());
26-
}
27-
return sb.reverse().toString();
32+
total += Math.min(countA, countB) * y;
33+
return total;
2834
}
2935
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy