2024-07-12 Daily Challenge

Today I have done leetcode's July LeetCoding Challenge with cpp.

July LeetCoding Challenge 12

Description

Maximum Score From Removing Substrings

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.
    <ul>
    	<li>For example, when removing <code>&quot;ab&quot;</code> from <code>&quot;c<u>ab</u>xbae&quot;</code> it becomes <code>&quot;cxbae&quot;</code>.</li>
    </ul>
    </li>
    <li>Remove substring <code>&quot;ba&quot;</code> and gain <code>y</code> points.
    <ul>
    	<li>For example, when removing <code>&quot;ba&quot;</code> from <code>&quot;cabx<u>ba</u>e&quot;</code> it becomes <code>&quot;cabxe&quot;</code>.</li>
    </ul>
    </li>
    

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.

Solution

class Solution {
public:
  int maximumGain(string s, int x, int y) {
    string bigger = "ab";
    string smaller = "ba";
    int sB = x;
    int sS = y;
    if(y > x) {
      swap(bigger, smaller);
      swap(sB, sS);
    }

    int answer = 0;
    vector<char> st;
    for(auto c : s) {
      if(c == bigger[1] && st.size() && st.back() == bigger[0]) {
        answer += sB;
        st.pop_back();
      } else {
        st.push_back(c);
      }
    }
    vector<char> anotherSt;
    for(auto c : st) {
      if(c == smaller[1] && anotherSt.size() && anotherSt.back() == smaller[0]) {
        answer += sS;
        anotherSt.pop_back();
      } else {
        anotherSt.push_back(c);
      }
    }
    return answer;
  }
};