Siddhartha Khanooja
Siddhartha Khanooja

Reputation: 67

Segmentation fault in test cases

So, the question is as follows: Given any array(reasonably large) of integers, return the maximum difference between any two elements in the array such that the larger element occurs at a higher index than the smaller element. Return -1, if no such pair is found. Example:

7 2 3 10 2 4 8 1

where the first element is the size of the array(or the number of lines being entered), and the rest are the elements. Sample output is 8(10-2) for the above.

My code is as follows:

int A[20],size;

scanf("%d",&size);
for(int i=0;i<size;i++){
scanf("%d\n",&A[i]);
}
int diff = A[1]-A[0];
int currsum = diff;
int maxsum = currsum;

for(int i=1; i<size-1; i++)
{
    // Calculate current difference for the loop
    diff = A[i+1]-A[i];

    // Calculate current sum for the loop
    if (currsum > 0)
       currsum += diff;
    else
       currsum = diff;

    // Update max sum(if needed)
    if (currsum > maxsum)
       maxsum = currsum;
}

printf("%d",maxsum);

This is a question from Hackerrank, but it runs for only three out of 10 possible testcases. The rest of the cases return a segmentation fault. Any idea would be helpful.

Upvotes: 0

Views: 1219

Answers (2)

Slh47
Slh47

Reputation: 1

Using pointers make this more important. First declare A as pointer of integers, then, read the first element of the array, using this integer you can allocate memory dynamically (malloc() or calloc() function) for your array A. so the size of A will dynamic and you can resize it in function of the first element.

Upvotes: 0

CinCout
CinCout

Reputation: 9619

As mentioned in the comments, you've declared A to hold just 20 integers. But the question can send up to 1,000,000 integers. That's the mistake!

Upvotes: 1

Related Questions