#2606
Find the Substring With Maximum Cost
MediumArrayHash TableStringDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a modified version of Kadane’s algorithm to find the maximum sum of a contiguous subarray, which in this case corresponds to the maximum cost of a substring. This is efficient and avoids the need to check all substrings explicitly.
⚙️
Algorithm
4 steps- 1Step 1: Create an array to store the values of each character in `s` based on `chars` and `vals`.
- 2Step 2: Initialize variables to track the current cost and maximum cost found.
- 3Step 3: Iterate through the value array and apply Kadane’s algorithm to find the maximum contiguous sum.
- 4Step 4: Return the maximum cost found, ensuring it is not negative.
solution.py20 lines
1# Full working Python code
2
3def calculate_cost(c, chars, vals):
4 if c in chars:
5 return vals[chars.index(c)]
6 return ord(c) - ord('a') + 1
7
8def max_cost_substring(s, chars, vals):
9 n = len(s)
10 values = [calculate_cost(s[i], chars, vals) for i in range(n)]
11 max_cost = 0
12 current_cost = 0
13 for value in values:
14 current_cost = max(value, current_cost + value)
15 max_cost = max(max_cost, current_cost)
16 return max_cost
17
18# Example usage:
19print(max_cost_substring("adaa", "d", [-1000])) # Output: 2
20ℹ
Complexity note: This complexity is due to the single pass through the string to calculate values and another pass to apply Kadane’s algorithm, making it linear in relation to the input size.
- 1Understanding character values is crucial to solving the problem efficiently.
- 2Kadane's algorithm is a powerful tool for finding maximum subarray sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.