Magicsheet logo

Find the Substring With Maximum Cost

Medium
69.9%
Updated 6/1/2025

Find the Substring With Maximum Cost

1. What is this problem about?

The Find the Substring With Maximum Cost interview question asks you to find a contiguous segment of a string that has the highest value (cost). Each character in the string has an associated cost. By default, 'a' is 1, 'b' is 2... 'z' is 26. However, you are also given a custom mapping for some characters. You need to find the maximum possible sum of costs among all possible substrings. The maximum cost must be at least 0 (since an empty substring has cost 0).

2. Why is this asked in interviews?

Companies like Amazon ask the Find the Substring With Maximum Cost coding problem to see if you can identify a standard algorithmic pattern hidden behind a unique problem description. This is a classic variation of the "Maximum Subarray Sum" problem. It evaluations your knowledge of Dynamic Programming interview patterns, specifically Kadane’s Algorithm.

3. Algorithmic pattern used

This problem is solved using Kadane’s Algorithm after a mapping step.

  1. Normalization: Map every character in the string to its integer cost using the default rules and the provided custom overrides.
  2. Kadane’s Step: Iterate through the numeric costs and maintain:
    • current_sum: The best sum ending at the current position.
    • max_sum: The best sum found so far.
  3. Transition: current_sum = max(0, current_sum + current_cost).
  4. Result: max_sum is the answer.

4. Example explanation

String: "abc", Custom: b = -10.

  1. Costs: a=1, b=-10, c=3.
  2. Scan:
    • Index 0 (1): curr=1, max=1.
    • Index 1 (-10): curr = max(0, 1 - 10) = 0.
    • Index 2 (3): curr = 3, max = 3. Result: 3. (Substring "c").

5. Common mistakes candidates make

  • Brute Force: Checking all O(N2)O(N^2) substrings, which is too slow for long strings.
  • Negative handling: Forgetting that if all substring sums are negative, the answer should be 0 (representing an empty substring).
  • Mapping errors: Incorrectly calculating the default value for characters not present in the custom mapping.

6. Interview preparation tip

Master Kadane’s Algorithm. It is the optimal O(N)O(N) solution for any "Maximum Subarray" problem. Whenever you see a requirement to find a "best contiguous segment," Kadane's should be your first consideration. This is a fundamental Array interview pattern.

Similar Questions