-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path23_Maximum_Score_From_Removing_Substrings.cpp
More file actions
87 lines (75 loc) · 2.25 KB
/
Copy path23_Maximum_Score_From_Removing_Substrings.cpp
File metadata and controls
87 lines (75 loc) · 2.25 KB
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
79
80
81
82
83
84
85
86
87
// 1717. Maximum Score From Removing Substrings
// Solved
// Medium
// Topics
// premium lock icon
// Companies
// Hint
// 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.
// Example 1:
// Input: s = "cdbcbbaaabab", x = 4, y = 5
// Output: 19
// Explanation:
// - Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
// - Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
// - Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
// - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
// Total score = 5 + 4 + 5 + 5 = 19.
// Example 2:
// Input: s = "aabbaaxybbaabb", x = 5, y = 4
// Output: 20
// Constraints:
// 1 <= s.length <= 105
// 1 <= x, y <= 104
// s consists of lowercase English letters.
class Solution
{
public:
int maximumGain(string s, int x, int y)
{
int aCount = 0;
int bCount = 0;
int lesser = min(x, y);
int result = 0;
for (char c : s)
{
if (c > 'b')
{
result += min(aCount, bCount) * lesser;
aCount = 0;
bCount = 0;
}
else if (c == 'a')
{
if (x < y && bCount > 0)
{
bCount--;
result += y;
}
else
{
aCount++;
}
}
else
{
if (x > y && aCount > 0)
{
aCount--;
result += x;
}
else
{
bCount++;
}
}
}
result += min(aCount, bCount) * lesser;
return result;
}
};