[JavaScript] Easy to understand - 2 solutions
SOLUTION 1\n\nWe use the sliding window to solve it. The left and right means both edges of the window.\n\nSo, we could meet 2 situations when we move the right
## SOLUTION 1\n\nWe use the sliding window to solve it. The `left` and `right` means both edges of the window.\n\nSo, we could meet 2 situations when we move the right edge from start to end:\n\n- The cost is less than `maxCost`: we could update the max length;\n- The cost is bigger than `maxCost`: we need to move the left edge to reduce cost.\n\nHere\'s the code:\n\n```js\nconst equalSubstring = (s, t, maxCost) => {\n  let max = 0;\n  for (let left = -1, right = 0; right < s.length; ++right) {\n    maxCost -= Math.abs(s.charCodeAt(right) - t.charCodeAt(right));\n    if (maxCost >= 0) {\n      right - left > max && (max = right - left);\n    } else {\n      while (maxCost < 0) {\n        ++left;\n        maxCost += Math.abs(s.charCodeAt(left) - t.charCodeAt(left));\n      }\n    }\n  }\n  return max;\n};\n```\n\n## SOLUTION 2\n\nHere\'s a more concise version of solution 1.\n\nWe move the right edge step by step just like solution 1. But the key point is that we also move the left edge step by step if it\'s necessary.\n\nBut why? It\'s pretty easy to find out that the window could be invalidated.\n\nLet\'s see, first of all, we only need to find out the longest substring which means we don\'t care about the others.\n\nThen, if we have a substring right now. There are only 2 situations:\n\n- We could find a longer one: the window will be validated naturally when we meet the longer one.\n- It\'s the longest one: we got the longest length even the current window may not be validated.\n\nSo, according to this, we could get this code:\n\n```js\nconst equalSubstring = (s, t, maxCost) => {\n  let left = -1;\n  for (let right = 0; right < s.length; ++right) {\n    maxCost -= Math.abs(s.charCodeAt(right) - t.charCodeAt(right));\n    if (maxCost < 0) {\n      ++left;\n      maxCost += Math.abs(s.charCodeAt(left) - t.charCodeAt(left));\n    }\n  }\n  return s.length - left - 1;\n};\n
['JavaScript']