Can anyone please explain what’s the problem with my code, it is correct for one test case but shows runtime error for other.
code- include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t–){
int n,m;
cin>>n>>m;
string s;
string k;
cin>>s;
cin>>k;
int mini=INT_MAX;
int res=0;
string str,final;
for(int i=0;i<=(n-m);i++)
{
str=s.substr(i,m);
int stri=stoi(str);
int key=stoi(k);
if(abs(stri-key)<mini){
mini=abs(stri-key);
final=str;
}
@rajchaurasiya
U are getting runtime error because of this line.
for(int i=0;i<=(n-m);i++)
the = is making problem of run time error and making it out of bound.
Well, there are some logical issues looking with your code, you can try below code to fix this error.
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
string s;
string k;
cin >> s;
cin >> k;
int mini = INT_MAX;
int res = 0;
string final;
for (int i = 0; i <= (n - m); i++) {
string str = s.substr(i, m);
int stri = stoi(str);
int key = stoi(k);
if (abs(stri - key) < mini) {
mini = abs(stri - key);
final = str;
}
}
for (int i = 0; i < m; i++) {
int diff = abs((k[i] - '0') - (final[i] - '0'));
if (diff > 5) {
diff = 10 - diff;
}
res += diff;
}
cout << res << endl;
}
return 0;
}