Given string str of lowercase alphabets and an array cost[], where cost[i] represents the cost of deletion of ith character in the given string. The task is to find the maximum possible cost to obtain a string having no adjacent pair of same characters, by deleting the same pair of consecutive characters.
Examples:
Input: str = “abaac”, cost = {1, 2, 3, 4, 5}
Output: 4
Explanation:
Remove character ‘a’ from position 4 in one based indexingInput: str = “abc”, cost = {1, 2, 3}
Output: 0
Explanation:
No consecutive characters are found.
Naive Approach: The simplest approach is to traverse the given string to check for each character from a to z if there are substrings having only that character. Follow the steps below to solve the problem:
- Traverse from a to z to check substrings having only that character.
- If any substring is found, calculate the sum for removal of each character and subtract the minimum cost from it.
- Add the above sum in the total count.
- Repeat the above steps for every substring.
- Print the total count.
Time Complexity: O(N*26), where N is the length of the given string
Auxiliary Space: O(N)
Efficient Approach: Follow the below steps to optimize the above approach:
- Traverse the given string over the range of indices [0, N – 2] and initialize a variable, say maxCost, to store the maximum possible cost.
- Check if characters S[i] and S[i+1] are equal.
- If adjacent characters are equal, then add the maximum cost from cost[i] and cost[i + 1] to maxCost and shift the minimum cost to right by setting cost[i + 1] = min(cost[i], cost[i + 1]).
- After traversing the given string, print the value of maxCost.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find maximum cost to // remove consecutive characters int Maxcost(string s, int cost[]) { // Initialize the count int count = 0; // Maximum cost int maxcost = 0, i = 0; // Traverse from 0 to len(s) - 2 while (i < s.size() - 1) { // If characters are identical if (s[i] == s[i + 1]) { // Add cost[i] if its maximum if (cost[i] > cost[i + 1]) maxcost += cost[i]; // Add cost[i + 1] // if its maximum else { maxcost += cost[i + 1]; cost[i + 1] = cost[i]; } } // Increment i i += 1; } // Return the final max count return maxcost; } // Driver Code int main() { // Given string s string s = "abaac"; // Given cost of removal int cost[] = {1, 2, 3, 4, 5}; // Function Call cout << Maxcost(s, cost); return 0; } // This is code contributed by gauravrajput1 |
Java
// Java program for the above approach import java.io.*; import java.util.*; class GFG{ // Function to find maximum cost to // remove consecutive characters static int Maxcost(String s, int []cost) { // Maximum cost int maxcost = 0; int i = 0; // Traverse from 0 to len(s) - 2 while (i < s.length() - 1) { // If characters are identical if (s.charAt(i) == s.charAt(i + 1)) { // Add cost[i] if its maximum if (cost[i] > cost[i + 1]) maxcost += cost[i]; // Add cost[i + 1] // if its maximum else { maxcost += cost[i + 1]; cost[i + 1] = cost[i]; } } // Increment i i++; } // Return the final max count return maxcost; } // Driver code public static void main (String[] args) { // Given string s String s = "abaac"; // Given cost of removal int []cost = { 1, 2, 3, 4, 5 }; // Function call System.out.print(Maxcost(s, cost)); } } // This code is contributed by code_hunt |
Python3
# Python3 program for the above approach # Function to find maximum cost to # remove consecutive characters def Maxcost(s, cost): # Initialize the count count = 0 # Maximum cost maxcost = 0 i = 0 # Traverse from 0 to len(s) - 2 while i < len(s) - 1: # If characters are identical if s[i] == s[i + 1]: # Add cost[i] if its maximum if cost[i] > cost[i + 1]: maxcost += cost[i] # Add cost[i + 1] if its # maximum else: maxcost += cost[i + 1] cost[i + 1] = cost[i] # Increment i i += 1 # Return the final max count return maxcost # Driver Code # Given string s s = "abaac" # Given cost of removal cost = [1, 2, 3, 4, 5] # Function Call print(Maxcost(s, cost)) |
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to find maximum cost to // remove consecutive characters static int Maxcost(string s, int []cost) { // Maximum cost int maxcost = 0; int i = 0; // Traverse from 0 to len(s) - 2 while (i < s.Length - 1) { // If characters are identical if (s[i] == s[i + 1]) { // Add cost[i] if its maximum if (cost[i] > cost[i + 1]) maxcost += cost[i]; // Add cost[i + 1] // if its maximum else { maxcost += cost[i + 1]; cost[i + 1] = cost[i]; } } // Increment i i++; } // Return the final max count return maxcost; } // Driver code public static void Main (string[] args) { // Given string s string s = "abaac"; // Given cost of removal int []cost = {1, 2, 3, 4, 5}; // Function call Console.Write(Maxcost(s, cost)); } } // This code is contributed by rutvik_56 |
4
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimum Cost of deletions such that string does not contains same consecutive characters
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Count characters to be shifted from the start or end of a string to obtain another string
- Remove first adjacent pairs of similar characters until possible
- Minimum adjacent swaps to group similar characters together
- Longest substring between any pair of occurrences ōf similar characters
- Make the string lexicographically smallest and non palindromic by swapping of adjacent pair of characters
- Rearrange string such that no pair of adjacent characters are of the same type
- Sum of indices of Characters removed to obtain an Empty String based on given conditions
- Minimum number of Appends of X or Y characters from the end to the front required to obtain given string
- Minimum cost to remove the spaces between characters of a String by rearranging the characters
- String with k distinct characters and no same characters adjacent
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Minimum number of deletions to make a string palindrome | Set 2
- Deletions of "01" or "10" in binary string to make it free from "01" or "10"
- Minimize deletions in a Binary String to remove all subsequences of the form "0101"
- Minimum number of deletions to make a string palindrome
- Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K
- Minimum string such that every adjacent character of given string is still adjacent
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

