Find the Substring With Maximum Cost
Problem
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.
The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0.
The value of the character is defined in the following way:
- If the character is not in the string
chars, then its value is its corresponding position (1-indexed) in the alphabet.- For example, the value of
'a'is1, the value of'b'is2, and so on. The value of'z'is26.
- For example, the value of
- Otherwise, assuming
iis the index where the character occurs in the stringchars, then its value isvals[i].
Return the maximum cost among all substrings of the string s.
Examples
Example 1
Input: s = "adaa", chars = "d", vals = [-1000]
Output: 2
Explanation: The value of the characters "a" and "d" is 1 and -1000 respectively.
The substring with the maximum cost is "aa" and its cost is 1 + 1 = 2.
It can be proven that 2 is the maximum cost.
Example 2
Input: s = "abc", chars = "abc", vals = [-1,-1,-1]
Output: 0
Explanation: The value of the characters "a", "b" and "c" is -1, -1, and -1 respectively.
The substring with the maximum cost is the empty substring "" and its cost is 0.
It can be proven that 0 is the maximum cost.
Constraints
1 <= s.length <= 10^5sconsist of lowercase English letters.1 <= chars.length <= 26charsconsist of distinct lowercase English letters.vals.length == chars.length-1000 <= vals[i] <= 1000
Solution
Method 1 – Sliding Window with Set
Intuition
To maximize the sum of a subarray with unique elements, we need to find continuous windows without repetitions, and among all such windows, choose the one with the highest sum.
Approach
- Use the sliding window technique with a Set to track unique elements.
- Maintain two pointers, start and end, to define the window boundaries.
- If nums[end] is not in the set, add it and update the sum.
- If it's a duplicate, remove elements from the left until nums[end] can be added without repetition.
- At each step, update the maximum sum.
Code
C++
class Solution {
public:
int maxSum(vector<int>& nums) {
unordered_set<int> seen;
int sum = 0, ans = INT_MIN, start = 0;
for (int end = 0; end < nums.size(); ++end) {
while (seen.count(nums[end])) {
seen.erase(nums[start]);
sum -= nums[start++];
}
if (nums[end] > 0) {
seen.insert(nums[end]);
sum += nums[end];
}
ans = max(ans, sum);
ans = max(ans, nums[end]);
}
return ans;
}
};
Java
class Solution {
int maxSum(int[] nums) {
Set<Integer> seen = new HashSet<>();
int sum = 0;
int max = Integer.MIN_VALUE;
for (int num : nums) {
if (num > 0 && seen.add(num)) {
sum += num;
}
max = Math.max(max, num);
}
return (sum > 0) ? sum : max;
}
}
Python
class Solution:
def maxSum(self, nums: list[int]) -> int:
seen: set[int] = set()
sum_: int = 0
max_: int = float('-inf')
for num in nums:
if num > 0 and num not in seen:
seen.add(num)
sum_ += num
max_ = max(max_, num)
return sum_ if sum_ > 0 else max_
Complexity
- ⏰ Time complexity:
O(n), since each element is processed at most twice (once added, once removed). - 🧺 Space complexity:
O(n), for the set storing unique elements.
Method 2 – Counting Unique Positives
Intuition
Instead of using a sliding window, we can simply keep all unique positive numbers and sum them. This works because we can delete any negative or duplicate numbers, and the sum of all unique positive numbers will be the answer.
For example, given [1,2,-1,-2,1,0,-1]:
- Remove all negatives: [1,2,1,0]
- Remove duplicates: [1,2,0]
- Sum: 1+2+0 = 3
Approach
- Check if all numbers are negative; if so, return the maximum.
- Use a set to collect unique positive numbers.
- Sum all unique positive numbers and return the result.
Code
C++
class Solution {
public:
int maxSum(vector<int>& nums) {
int n = nums.size();
if (n == 1) return nums[0];
int max_one = *max_element(nums.begin(), nums.end());
if (max_one < 0) return max_one;
unordered_set<int> seen;
int ans = 0;
for (int num : nums) {
if (num > 0 && !seen.count(num)) {
seen.insert(num);
ans += num;
}
}
return ans;
}
};
Java
class Solution {
public int maxSum(int[] nums) {
int n = nums.length;
if (n == 1) {
return nums[0];
}
int max_one = Arrays.stream(nums).max().getAsInt();
if (max_one < 0) {
return max_one;
}
Set<Integer> seen = new HashSet<>();
int maxSum = 0;
for (int num : nums) {
if (num > 0 && !seen.contains(num)) {
seen.add(num);
maxSum += num;
}
}
return maxSum;
}
}
Python
class Solution:
def maxSum(self, nums: list[int]) -> int:
n: int = len(nums)
if n == 1:
return nums[0]
max_one: int = max(nums)
if max_one < 0:
return max_one
seen: set[int] = set()
ans: int = 0
for num in nums:
if num > 0 and num not in seen:
seen.add(num)
ans += num
return ans
Complexity
- ⏰ Time complexity:
O(n), each element is checked once. - 🧺 Space complexity:
O(n), for the set storing unique positives.