LeetCode //C - 1208. Get Equal Substrings Within Budget

1208. Get Equal Substrings Within Budget

You are given two strings s and t of the same length and an integer maxCost.

You want to change s to t. Changing the ith character of s to ith character of t costs |si - ti| (i.e., the absolute difference between the ASCII values of the characters).

Return 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. If there is no substring from s that can be changed to its corresponding substring from t, return 0.

Example 1:

Input: s = "abcd", t = "bcdf", maxCost = 3

Output: 3

Explanation: "abc" of s can change to "bcd".

That costs 3, so the maximum length is 3.

Example 2:

Input: s = "abcd", t = "cdef", maxCost = 3

Output: 1

Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.

Example 3:

Input: s = "abcd", t = "acde", maxCost = 0

Output: 1

Explanation: You cannot make any change, so the maximum length is 1.

Constraints:
  • 1 < = s . l e n g t h < = 10 5 1 <= s.length <= 10^5 1<=s.length<=105
  • t.length == s.length
  • 0 < = m a x C o s t < = 10 6 0 <= maxCost <= 10^6 0<=maxCost<=106
  • s and t consist of only lowercase English letters.

From: LeetCode

Link: 1208. Get Equal Substrings Within Budget


Solution:

Ideas:

Use a sliding window: expand the right pointer while adding character costs, and shrink the left pointer whenever the total cost exceeds maxCost, tracking the maximum valid window length.

Code:
c 复制代码
#include <stdlib.h>

int equalSubstring(char* s, char* t, int maxCost) {
    int n = 0;
    while (s[n] != '\0') n++;

    int l = 0;
    int cost = 0;
    int ans = 0;

    for (int r = 0; r < n; r++) {
        cost += abs(s[r] - t[r]);

        while (cost > maxCost) {
            cost -= abs(s[l] - t[l]);
            l++;
        }

        int len = r - l + 1;
        if (len > ans) ans = len;
    }

    return ans;
}
相关推荐
yi0115 分钟前
LeetCode 15:三数之和|排序 + 双指针,如何避免重复答案?
笔记·python·算法·leetcode·双指针
Zwawa11 分钟前
把 AO 接回来:黑线和白底之间到底差了多少
c语言·单片机·嵌入式
-dzk-21 分钟前
【多维动态规划】LC 1143.最长公共子序列
算法·动态规划
C++ 老炮儿的技术栈26 分钟前
char (*csConnectName)[256]; 和 char csConnectName [256] 有什么区别
java·c语言·开发语言·c++·人工智能·算法·c
Omics Pro36 分钟前
全新可重分析!代谢组质谱专用
数据库·人工智能·算法·机器学习·自然语言处理
Nebula_g36 分钟前
JavaSE加强:线程Thread(线程安全重点)
java·开发语言·jvm·算法·javase·技术栈
一只废狗狗狗狗狗狗狗狗狗37 分钟前
Network架构1——卷积神经网络CNN
人工智能·算法·cnn
是希燃亚44 分钟前
AI Agent 的未来,可能不是更强,而是更简单
算法·架构
alphaTao1 小时前
LeetCode 每日一题 2026/10/5-2026/10/11
算法·leetcode
liliangcsdn1 小时前
现金流指标的探索和分析
大数据·算法