Program to find cost to remove consecutive duplicate characters with costs in C++?


Suppose we have a string with lowercase letters and we also have a list of non-negative values called costs, the string and the list have the same length. We can delete character s[i] for cost costs[i], and then both s[i] and costs[i] is removed. We have to find the minimum cost to delete all consecutively repeating characters.

So, if the input is like s = "xxyyx" nums = [2, 3, 10, 4, 6], then the output will be 6, as we can delete s[0] and s[3] for a total cost of 2 + 4 = 6.

To solve this, we will follow these steps

  • Define one stack st

  • cost := 0

  • for initialize i := 0, when i < size of s, update (increase i by 1), do:

    • if size of st is not 0 and s[top of st] is same as s[i], then:

      • if nums[top of st] > nums[i], then:

        • cost := cost + nums[i]

      • otherwise:

        • cost := cost + nums[top of st]

        • pop element from st

        • push i into st

    • otherwise

      • push i into st

  • return cost

Let us see the following implementation to get better understanding

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;

class Solution {
   public:
   int solve(string s, vector<int>& nums) {
      stack<int> st;
      int cost = 0;
      for (int i = 0; i < s.size(); ++i) {
         if (st.size() && s[st.top()] == s[i]) {
            if (nums[st.top()] > nums[i]) {
               cost += nums[i];
            } else {
               cost += nums[st.top()];
               st.pop();
               st.push(i);
            }
         } else {
            st.push(i);
         }
      }
      return cost;
   }
};


int solve(string s, vector<int>& nums) {
   return (new Solution())->solve(s, nums);
}

main(){
   vector<int> v = {2, 3, 10, 4, 6};
   string s = "xxyyx";
   cout << solve(s, v);
}

Input

"xxyyx",{2,3,10,4,6}

Output

6

Updated on: 10-Nov-2020

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements