Second Largest Element Solution
unknown
c_cpp
a year ago
807 B
4
Indexable
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 ; }
Editor is loading...
Leave a Comment