Official
C - Second Best Editorial by en_translator
The second largest value can be found in, for example, the sequence \(A'\) obtained by sorting \(A\). When \(A\) is sorted in ascending order, the second last value, or \(A'_{N-1}\), is the second largest value.
Next, find the position of that value in \(A\) using for
and if
statements.
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for(auto &v : a) cin >> v;
auto b = a;
sort(b.begin(), b.end());
int tar = b[n - 2];
for(int i = 0; i < n; i++) {
if(a[i] == tar) {
cout << i + 1 << endl;
}
}
}
posted:
last update: