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.
1#include <stdio.h>
2#include <string.h>
3
4int maxScore(char* s, int x, int y) {
5 int score = 0;
6 char stack[strlen(s)];
7 int top = -1;
8 char first = x > y ? 'a' : 'b';
9 char second = x > y ? 'b' : 'a';
10 int firstPoints = x > y ? x : y;
11 int secondPoints = x > y ? y : x;
12
13 // Remove the higher score patterns first
14 for (int i = 0; s[i] != '\0'; i++) {
15 if (top >= 0 && stack[top] == first && s[i] == second) {
16 top--; // pop from stack
17 score += firstPoints;
18 } else {
19 stack[++top] = s[i]; // push onto stack
20 }
21 }
22
23 // Second pass to remove remaining patterns
24 int newTop = -1;
25 for (int i = 0; i <= top; i++) {
26 if (newTop >= 0 && stack[newTop] == second && stack[i] == first) {
27 newTop--; // pop
28 score += secondPoints;
29 } else {
30 stack[++newTop] = stack[i]; // push
31 }
32 }
33
34 return score;
35}
36
37int main() {
38 char s[] = "cdbcbbaaabab";
39 int x = 4;
40 int y = 5;
41 printf("%d\n", maxScore(s, x, y));
42 return 0;
43}
This solution leverages a stack to remove 'ab' or 'ba' substrings based on their point values. The approach consists of two sweeps across the input string: one for the highest point substring and another for the remaining to maximize the score.
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 Java solution employs a StringBuilder for dynamic string modification, ensuring minimal pointer movement and swift modification of input for maximum score extraction through two careful scans.