
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Get Equal Substrings Within Budget in C++
Suppose we have given two strings s and t of the same length. We want to change s to t. Changing the i-th character of s to i-th character of t will assign cost as |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters. We have also given an integer maxCost. We have to find the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost.
So if the input is like s = “abcd” and t = “bcdf”, then the maxCost will be 3, this is because “abc” in s, can be converted to “bcd”, that will cost 3, then the output will be 3.
To solve this, we will follow these steps −
j := 0, sum := 0 and ret := 0
for i in range 0 to minimum of s and t sizes
increase sum by |s[i] – t[i]|
while sum > maxCost
decrease sum by |s[i] – t[i]|
increase j by 1
ret := max of ret and (i – j + 1)
return ret
Example (C++)
Let us see the following implementation to get a better understanding −
class Solution { public: int equalSubstring(string s, string t, int maxCost) { int j = 0; int sum = 0; int ret = 0; for(int i = 0; i < min((int)s.size(), (int)t.size()); i++){ sum += abs(s[i] - t[i]); while(sum > maxCost){ sum -= abs(s[j] - t[j]); j++; } ret = max(ret, i - j + 1); } return ret; } };
Input
"abcd" "bcdf" 3
Output
3
- Related Articles
- Find all substrings combinations within arrays in JavaScript
- Adding paragraph tag to substrings within a string in JavaScript
- Count Substrings with equal number of 0s, 1s and 2s in C++
- How Can Project Managers Ensure Successful Project Delivery Within Time and Budget Constraints?
- Get the types nested within the current Type C#
- Get a specific type nested within the current Type in C#
- Count Binary Substrings in C++
- Distinct Echo Substrings in C++
- Get all substrings of a string in JavaScript recursively
- How Can You Get Project Management Certification with Zero Budget?
- Unique Substrings in Wraparound String in C++
- Program to find out the number of pairs of equal substrings in Python
- Count of total anagram substrings in C++
- Consumer Budget
- Government Budget
