Minimum Deletion Cost to Avoid Repeating LettersMinimum Deletion Cost to Avoid Repeating Letters

Minimum Deletion Cost to Avoid Repeating Letters

This is a Leet Code problem (1578 – Minimum Deletion Cost to Avoid Repeating Letters) solved in Java, the problem description is:

Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s.

Return the minimum cost of deletions such that there are no two identical letters next to each other.

Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change.

Example 1:

Input: s = "abaac", cost = [1,2,3,4,5]
Output: 3
Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other).

Example 2:

Input: s = "abc", cost = [1,2,3]
Output: 0
Explanation: You don't need to delete any character because there are no identical letters next to each other.

Example 3:

Input: s = "aabaa", cost = [1,2,3,4,1]
Output: 2
Explanation: Delete the first and the last character, getting the string ("aba").

Constraints:

  • s.length == cost.length
  • 1 <= s.length, cost.length <= 10^5
  • 1 <= cost[i] <= 10^4
  • s contains only lowercase English letters.

Solution:

class Solution {
    public int minCost(String s, int[] cost) {
    int c=0;
    int total = cost[0];
    int highest = cost[0];

    for(int i=1;i&amp;amp;amp;lt;s.length();i++){
        if(s.charAt(i)!=s.charAt(i-1)){
            c+=total - highest;
            total = cost[i];
            highest = cost[i];
        } else {
            total += cost[i];
            highest = Math.max(highest,cost[i]);
        }
    }
    c+= total - highest;
    return c;
    }
}

 

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.