The Lead Game | CodeChef

For some inputs my code is working but for some it is not.
please help me to find the problem. i am getting SIGSEGV error.

#include <bits/stdc++.h>

using namespace std;

int main() {
int n;
cin>>n;
int p1[n],p2[n],lead[n],p[n];

for(int i=0;i<n;i++)
    cin>>p1[i]>>p2[i];
    
lead[0]=abs(p1[0]-p2[0]);

  
    if(p1[0]>p2[0])
        p[0]=1;
    else
        p[0]=2;
    
for (int i=1;i<n;i++)
{
    p1[i]=p1[i]+p1[i-1];
    p2[i]=p2[i]+p2[i-1];
    lead[i]=abs(p1[i]-p2[i]);
    
    if(p1[i]>p2[i])
        p[i]=1;
    else
        p[i]=2;
}

int largest,pos;
largest = lead[0];
for(int i=1; i<n; i++)
{
if(lead[i]>largest)
{
largest = lead[i];
pos = i;
}
}
cout<<p[pos]<<" "<<largest;
return 0;
}

You have not intialized pos variable with zero( use this int largest,pos=0). It’s storing a gerabage value and when you trying to access the p[pos] it’s giving SIGSEGV.

2 Likes

Thank you …It worked :metal: