FastPrepMinimum Deletion Cost for Distinct Adjacent Characters

Minimum Deletion Cost for Distinct Adjacent Characters

HSBC logoHSBC● MediumFULLTIMEOA

Problem statement

You are given a string S and an array C. Deleting the character at original index i costs C[i]. Other characters keep their original deletion costs after a deletion.

Return the minimum total cost needed to make every pair of adjacent characters different. You may delete any number of characters, including none.

Function

solution(S: String, C: int[]) → int

Examples

Example 1

S = "abccbd"C = [0,1,2,3,4,5]return = 2

Delete the first c, whose original cost is 2. The remaining string is abcbd, which has no equal adjacent characters.

Example 2

S = "aabbcc"C = [1,2,1,2,1,2]return = 3

Delete one character of cost 1 from each of the three equal-character runs. The total cost is 1 + 1 + 1 = 3.

Example 3

S = "aaaa"C = [3,4,5,6]return = 12

Keep the last a, whose cost is 6. Delete the other three for 3 + 4 + 5 = 12.

Example 4

S = "ababa"C = [10,5,10,5,10]return = 0

All adjacent characters already differ, so no deletion is needed.

Constraints

  • 1 <= S.length <= 10^5.
  • C.length equals S.length.
  • S contains only lowercase English letters.
  • 0 <= C[i] <= 10^4.

More HSBC problems

See HSBC hiring insights
Saved
public int solution(String S, int[] C) {
    // Write your solution here.
}
S"abccbd"
C[0,1,2,3,4,5]
expected2
Checking account…