Skip to content

2606. Find the Substring With Maximum Cost 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int maximumCostSubstring(string s, string chars, vector<int>& vals) {
    int ans = 0;
    int cost = 0;
    vector<int> costs(26);  // costs[i] := the cost of 'a' + i

    iota(costs.begin(), costs.end(), 1);

    for (int i = 0; i < chars.size(); ++i)
      costs[chars[i] - 'a'] = vals[i];

    for (const char c : s) {
      cost = max(0, cost + costs[c - 'a']);
      ans = max(ans, cost);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int maximumCostSubstring(String s, String chars, int[] vals) {
    int ans = 0;
    int cost = 0;
    int[] costs = new int[26]; // costs[i] := the cost of 'a' + i

    for (int i = 0; i < 26; ++i)
      costs[i] = i + 1;

    for (int i = 0; i < chars.length(); ++i)
      costs[chars.charAt(i) - 'a'] = vals[i];

    for (final char c : s.toCharArray()) {
      cost = Math.max(0, cost + costs[c - 'a']);
      ans = Math.max(ans, cost);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maximumCostSubstring(self, s: str, chars: str, vals: list[int]) -> int:
    ans = 0
    cost = 0
    costs = [i for i in range(1, 27)]  # costs[i] := the cost of 'a' + i

    for c, val in zip(chars, vals):
      costs[string.ascii_lowercase.index(c)] = val

    for c in s:
      cost = max(0, cost + costs[string.ascii_lowercase.index(c)])
      ans = max(ans, cost)

    return ans