Sponsored
Sponsored
In this approach, we prioritize removing the substring with a higher score first. We utilize a stack to efficiently traverse and remove substrings from the string. Given two substrings 'ab' and 'ba', and their scores x and y, we decide which to remove first based on the higher score. The stack helps in processing the string in a single pass, adding character by character and checking for the target substring ending each time.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack used in substring removal.
1import java.util.Stack;
2
3public class MaxScore {
4 public static int maxScore(String s, int x, int y) {
5 int score = 0;
6 Stack<Character> stack = new Stack<>();
7 char first = x > y ? 'a' : 'b';
8 char second = x > y ? 'b' : 'a';
9 int firstPoints = x > y ? x : y;
10 int secondPoints = x > y ? y : x;
11
12 // Remove the higher score patterns first
13 for (char c : s.toCharArray()) {
14 if (!stack.isEmpty() && stack.peek() == first && c == second) {
15 stack.pop();
16 score += firstPoints;
17 } else {
18 stack.push(c);
19 }
20 }
21
22 // Second pass to remove remaining patterns
23 Stack<Character> secondStack = new Stack<>();
24 while (!stack.isEmpty()) {
25 char c = stack.pop();
26 if (!secondStack.isEmpty() && secondStack.peek() == second && c == first) {
27 secondStack.pop();
28 score += secondPoints;
29 } else {
30 secondStack.push(c);
31 }
32 }
33
34 return score;
35 }
36
37 public static void main(String[] args) {
38 String s = "cdbcbbaaabab";
39 int x = 4;
40 int y = 5;
41 System.out.println(maxScore(s, x, y));
42 }
43}
This Java implementation utilizes two stacks for parsing and modifying the string similarly to the other solutions. The first stack manages the primary sweep for the higher score, and the second stack handles the remaining patterns.
The Two-Pointer approach leverages two pointers to parse through the string and eliminate substrings optimally. By managing two scanning points, determining which pattern to remove can be executed with minimal operations, optimizing score calculation effectively.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to stack arrays used to manage character tracking.
1
This JavaScript solution applies a straightforward two-pass parsing using array behaviors for stack operations. It establishes a methodical approach by choosing higher score eliminations first, then resolving the rest to extract scores maximally.