Get Equal Substrings Within Budget in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 31-Mar-2020 09:16:39
Advertisements