简体   繁体   中英

I keep getting SIGTSTP error for my code but I am not able to figure out where is my code going out of bounds

I am trying to find the largest sum for the difference between 3 numbers in a given list inputed by the user but I keep getting SIGTSTP and I am not able to understand where my code in going out of bounds.

Here is my code:

#include <iostream>
#include<vector>
#include <algorithm>
using namespace std;

int main() {
    // your code goes here
    int t,n,z;
    vector<long long int> a;
    long long int max,min,k,x,sum;
    cin>>t;
    while(t--){
        cin>>n;
        while(n--){
            cin>>x;
            a.push_back(x);
        }
     max = *max_element(a.begin(),a.end());
     min = *min_element(a.begin(),a.end());
    
     int i=0,k=0;
     //to find a element other than minimum or maximum element and assign it to k
     while(i<3){
         if(a[i]==max || a[i]==min)
           continue;
         else
          k=a[i];
        i++;
     }
     if(k==0)
      k=a[0];
     //sum
     sum = abs(max-min) + abs(k-min) + abs(max-k);
     cout<<sum;
    }
    return 0;
}

Input given:

3
3
2 7 5
3
3 3 3
5
2 2 2 2 5
 int i=0,k=0;
 while(i<3){
     if(a[i]==max || a[i]==min)
       continue;
     else
      k=a[i];
 }

You set i to zero when you enter the loop. The loop will not exit so long as i is less than 3. But nothing in the loop changes the value of i . So i will always be less than 3 and the loop will never exit.

Learn to do some basic troubleshooting such as using a debugger or adding logging.

Also, there are no comments in this code. I have no idea what this loop is supposed to do, so can't give you specific suggestions on how to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM