-
Notifications
You must be signed in to change notification settings - Fork 0
/
1208. Get Equal Substrings Within Budget
97 lines (60 loc) · 1.67 KB
/
1208. Get Equal Substrings Within Budget
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Solution {
public int equalSubstring(String s, String t, int maxCost)
{
int[] arr = new int[s.length()];
char[] ch = s.toCharArray(), target = t.toCharArray();
for(int i=0; i<arr.length; i++)
{
arr[i] = Math.abs(ch[i] - target[i]);
}
int cost=0, start=0, end=0, result=0;
while(start < arr.length && end <arr.length)
{
cost = cost+arr[end++];
if(cost <= maxCost)
{
result = Math.max(result, end - start);
}
else
{
while(cost > maxCost)
{
cost = cost-arr[start++];
}
}
}
return result;
/*
RUNTIME 6 MS , MEMORY 43.40 MB
int[] diff = new int[s.length()];
for(int i=0; i<s.length(); i++)
{
diff[i] = Math.abs(s.charAt(i) - t.charAt(i));
}
int start = 0, count = 0;
for(int i=0; i<s.length(); i++)
{
maxCost = maxCost - diff[i];
while(maxCost <0)
{
maxCost = maxCost + diff[start++];
}
count = Math.max(count, i-start+1);
}
return count;
*/
/*
RUNTIME 9 MS , MEMORY 42.95 MB
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;
*/
}
}