Help -Getting runtime error in FAIRELCT

I am getting runtime error on my code please help!
Problem=https://www.codechef.com/problems/FAIRELCT
Mycode=
#include <bits/stdc++.h> // header file includes every Standard library
using namespace std;
long long sum(long long vec[],long long n)
{
long long summ=0;
for(long long i=0;i<n;i++)
{
summ+=vec[i];
}
return summ;
}

int main() {

long long t;
cin>>t;
while(t–)
{
long long n,m,result=0;
cin>>n>>m;
long long vecn[n];
long long vecm[m];
for(long long i=0;i<n;i++)
{

    cin>>vecn[i];
}
for(long long i=0;i<m;i++)
{
    cin>>vecm[i];
}
long long j=m-1;
long long i=0;
sort(vecn,vecn+n);
sort(vecm,vecm+m);
while(((j>=0) and (i<m))and (sum(vecn,n)<=sum(vecm,m)))
{
    swap(vecn[i],vecm[j]);
    result++;
    j--;
    i++;


}
if(sum(vecn,n)<=sum(vecm,m))
cout<<-1<<endl;
else
    cout<<result<<endl;

}

return 0;
}

:face_with_raised_eyebrow:

The code you posted is uncompilable (Please format your code in future! :slight_smile: ), so I’ll use this solution:

[simon@simon-laptop][19:42:51]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling pradyumnt-FAIRELCT.cpp
+ g++ -std=c++14 pradyumnt-FAIRELCT.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv -fno-sanitize-recover
+ set +x
Successful
[simon@simon-laptop][19:42:58]
[~/devel/hackerrank/otherpeoples]>echo "1
1 3
1
1000 1000 1000
" | ./a.out
pradyumnt-FAIRELCT.cpp:40:24: runtime error: index 2 out of bounds for type 'long long int [*]'
1 Like

Bro,i am not using vector .I am using array.

1 Like

can you please tell me what’s the problrm??

Pretty sure I did :slight_smile: Replace and (i<m) with and (i < n) and the crash should go away, at least.

1 Like

oh right i did a mistake ,it should be (i<n).Thanks bro

1 Like