Approach
Stack-based processing
For Maximum Score From Removing Substrings, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 39 lines of Java from the credited upstream file 1717.java.
- The implementation keeps its working state in language-native values and containers.
- 2 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maximumGain(String s, int x, int y) {3 4 5 6 7 8 return x > y ? gain(s, "ab", x, "ba", y) : gain(s, "ba", y, "ab", x);9 }10 11 12 13 private int gain(final String s, final String sub1, int point1, final String sub2, int point2) {14 int points = 0;15 Stack<Character> stack1 = new Stack<>();16 Stack<Character> stack2 = new Stack<>();17 18 19 for (final char c : s.toCharArray())20 if (!stack1.isEmpty() && stack1.peek() == sub1.charAt(0) && c == sub1.charAt(1)) {21 stack1.pop();22 points += point1;23 } else {24 stack1.push(c);25 }26 27 28 for (final char c : stack1)29 if (!stack2.isEmpty() && stack2.peek() == sub2.charAt(0) && c == sub2.charAt(1)) {30 stack2.pop();31 points += point2;32 } else {33 stack2.push(c);34 }35 36 return points;37 }38}39