Skip to content

Commit 423f2c5

Browse files
authored
Create Find the Substring With Maximum Cost.py
1 parent a86a983 commit 423f2c5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.
3+
4+
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.
5+
6+
The value of the character is defined in the following way:
7+
8+
If the character is not in the string chars, then its value is its corresponding position (1-indexed) in the alphabet.
9+
For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26.
10+
Otherwise, assuming i is the index where the character occurs in the string chars, then its value is vals[i].
11+
Return the maximum cost among all substrings of the string s.
12+
'''
13+
14+
15+
16+
class Solution:
17+
def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int:
18+
19+
cost1 = dict(zip(chars, vals))
20+
21+
ind = [i for i in range(1, 27)]
22+
val = string.ascii_lowercase
23+
24+
cost = dict(zip(val, ind))
25+
26+
for k, v in cost1.items():
27+
if k in cost:
28+
cost[k] = v
29+
30+
max_cost = 0
31+
cur_cost = 0
32+
for i in range(len(s)):
33+
34+
cur_cost += cost[s[i]]
35+
36+
if cur_cost < 0:
37+
cur_cost = 0
38+
max_cost = max(cur_cost, max_cost)
39+
print(max_cost)
40+
return max_cost

0 commit comments

Comments
 (0)