Leetcode 2606: Find the Substring With Maximum Cost

grid47
grid47
Exploring patterns and algorithms
Feb 20, 2024 6 min read

You are given a string s, a string chars of distinct characters, and an integer array vals of the same length as chars. The value of each character is determined by either its position in the alphabet or a corresponding value in the vals array if it is present in chars. The cost of a substring is the sum of the values of each character in that substring. Your goal is to find the maximum cost of any substring of s.
Problem
Approach
Steps
Complexity
Input: You are given a string s consisting of lowercase English letters, a string chars with distinct lowercase letters, and an integer array vals with values corresponding to each character in chars.
Example: s = 'xyz', chars = 'xy', vals = [10, 20]
Constraints:
• 1 <= s.length <= 10^5
• 1 <= chars.length <= 26
• chars consists of distinct lowercase English letters
• vals.length == chars.length
• -1000 <= vals[i] <= 1000
Output: Return the maximum cost among all substrings of the string s, where the cost of a substring is the sum of the values of its characters.
Example: Output: 30
Constraints:
• The output is a single integer representing the maximum cost of any substring.
Goal: To determine the maximum cost among all substrings by efficiently calculating the value of each substring.
Steps:
• First, create a map where each character in the string s gets a corresponding value based on chars and vals.
• For characters not present in chars, assign them their position in the alphabet.
• Use a sliding window or dynamic programming approach to calculate the maximum possible sum of character values in any substring.
Goal: Ensure the solution works within the time limit by efficiently calculating the cost for large strings.
Steps:
• The string s can have up to 100,000 characters.
• The chars string has at most 26 characters (distinct lowercase letters).
Assumptions:
• The characters in s are all lowercase English letters.
• The vals array corresponds to the characters in chars.
Input: s = 'abc', chars = 'abc', vals = [-1, -1, -1]
Explanation: In this case, each character in 'abc' has a value of -1, so the best substring with the maximum cost is the empty string, with a cost of 0.

Input: s = 'adaa', chars = 'd', vals = [-1000]
Explanation: In this example, the value of 'a' is 1 and 'd' is -1000. The maximum cost comes from the substring 'aa', with a total cost of 2.

Link to LeetCode Lab


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