-
Notifications
You must be signed in to change notification settings - Fork 0
/
equalSubstring.cpp
35 lines (33 loc) · 943 Bytes
/
equalSubstring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
class Solution {
public:
int binarySearch(const vector<int>& accDiff, int endIndex, int target) {
int low = 0, high = endIndex;
while (low < high) {
int mid = (high - low) / 2 + low;
if (accDiff[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
int equalSubstring(string s, string t, int maxCost) {
int n = s.length();
vector<int> accDiff(n + 1, 0);
for (int i = 0; i < n; i++) {
accDiff[i + 1] = accDiff[i] + abs(s[i] - t[i]);
}
int maxLength = 0;
for (int i = 1; i <= n; i++) {
int start = binarySearch(accDiff, i, accDiff[i] - maxCost);
maxLength = max(maxLength, i - start);
}
return maxLength;
}
};