Second Largest Element Solution

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
807 B
1
Indexable
Never
vector<int> getSecondOrderElements(int n, vector<int> a) {
    // Write your code here.
    vector<int> tempArr;

    int smallest = 0, largest = 0;

    for(int i = 0; i < n; i++){
        if(a[i] > a[largest]){
            largest = i ;
        }
        if(a[i] < a[smallest]){
            smallest  = i;
        }
    }

    int second_smallest = (smallest == 0) ? 1 : 0 ; 
    int second_largest = (largest == 0) ? 1 : 0 ; 

    for(int i = 0; i< n; i++){
        if(a[i] < a[second_smallest] && i != smallest){
            second_smallest = i ;
        }
        if(a[i] > a[second_largest] && i != largest){
            second_largest = i;
        }
    }

    tempArr.push_back(a[second_largest]);
    tempArr.push_back(a[second_smallest]);

    return tempArr ;

}
Leave a Comment