|
| 1 | +/** |
| 2 | + * 2606. Find the Substring With Maximum Cost |
| 3 | + * https://leetcode.com/problems/find-the-substring-with-maximum-cost/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a string s, a string chars of distinct characters and an integer array vals of |
| 7 | + * the same length as chars. |
| 8 | + * |
| 9 | + * The cost of the substring is the sum of the values of each character in the substring. The |
| 10 | + * cost of an empty string is considered 0. |
| 11 | + * |
| 12 | + * The value of the character is defined in the following way: |
| 13 | + * - If the character is not in the string chars, then its value is its corresponding position |
| 14 | + * (1-indexed) in the alphabet. |
| 15 | + * - For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26. |
| 16 | + * - Otherwise, assuming i is the index where the character occurs in the string chars, then its |
| 17 | + * value is vals[i]. |
| 18 | + * |
| 19 | + * Return the maximum cost among all substrings of the string s. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} s |
| 24 | + * @param {string} chars |
| 25 | + * @param {number[]} vals |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var maximumCostSubstring = function(s, chars, vals) { |
| 29 | + const charValues = new Array(26).fill().map((_, i) => i + 1); |
| 30 | + for (let i = 0; i < chars.length; i++) { |
| 31 | + charValues[chars.charCodeAt(i) - 97] = vals[i]; |
| 32 | + } |
| 33 | + |
| 34 | + let result = 0; |
| 35 | + let currentCost = 0; |
| 36 | + for (const char of s) { |
| 37 | + currentCost = Math.max(0, currentCost + charValues[char.charCodeAt(0) - 97]); |
| 38 | + result = Math.max(result, currentCost); |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | +}; |
0 commit comments