Skip to content

1208. Get Equal Substrings Within Budget 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int equalSubstring(string s, string t, int maxCost) {
    int j = 0;
    for (int i = 0; i < s.length(); ++i) {
      maxCost -= abs(s[i] - t[i]);
      if (maxCost < 0)
        maxCost += abs(s[j] - t[j++]);
    }

    return s.length() - j;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int equalSubstring(String s, String t, int maxCost) {
    int j = 0;
    for (int i = 0; i < s.length(); ++i) {
      maxCost -= Math.abs(s.charAt(i) - t.charAt(i));
      if (maxCost < 0)
        maxCost += Math.abs(s.charAt(j) - t.charAt(j++));
    }

    return s.length() - j;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
    j = 0
    for i in range(len(s)):
      maxCost -= abs(ord(s[i]) - ord(t[i]))
      if maxCost < 0:
        maxCost += abs(ord(s[j]) - ord(t[j]))
        j += 1

    return len(s) - j