Leetcode 1717: Maximum Score From Removing Substrings

grid47
grid47
Exploring patterns and algorithms
May 19, 2024 6 min read

You are given a string s and two integers x and y. You can perform two types of operations any number of times:

  1. Remove the substring “ab” and gain x points.
  2. Remove the substring “ba” and gain y points.

Each time a substring is removed, the characters are deleted from the string, and the corresponding points are added to your total score. Your task is to maximize the total score after applying these operations any number of times.

Problem
Approach
Steps
Complexity
Input: You are given a string `s` of lowercase English letters and two integers `x` and `y`.
Example: Input: s = "dcbaba", x = 3, y = 4
Constraints:
• 1 <= s.length <= 100000
• 1 <= x, y <= 10000
• s consists of lowercase English letters.
Output: Return the maximum points you can gain after applying the operations.
Example: Output: 12
Constraints:
• The result will be an integer.
Goal: The goal is to maximize the score by performing the optimal sequence of substring removal operations.
Steps:
• 1. Check which substring, 'ab' or 'ba', gives the higher points and prioritize removing that.
• 2. Use a greedy approach to simulate the removals of 'ab' or 'ba' from the string, adjusting the score accordingly.
• 3. After each removal, check if further operations can be performed until no more 'ab' or 'ba' can be removed.
Goal: The problem needs to efficiently handle strings of up to 100,000 characters.
Steps:
• The solution should run in O(n) time complexity.
Assumptions:
• The string `s` will always be valid and consist of lowercase English letters.
• The operations on 'ab' and 'ba' are independent, and they can be performed multiple times.
Input: Input: s = "dcbaba", x = 3, y = 4
Explanation: In this case, removing 'ba' first (giving 4 points) and then 'ab' (giving 3 points) results in a total score of 12.

Input: Input: s = "aabbab", x = 5, y = 4
Explanation: First, remove 'ab' (5 points), then remove 'ba' (4 points), giving a total score of 9.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus