Challenge: Biggest Number
Completed
Read n numbers and print the largest and its position (index from 0). If it appears more than once, give the first position.
Input
Line 1: n (n ≥ 1). Line 2: n whole numbers.
Output
<largest> at index <i>
Example
Input
5 3 9 2 9 1
Output
9 at index 1
Editor
C++
Hints
Remember the index of the best value so far.
Use > (not >=) so the first position wins a tie.
Solution explanation
One pass over the vector: O(n).
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
int best = 0;
for (int i = 1; i < n; i++)
if (v[i] > v[best]) best = i;
cout << v[best] << " at index " << best << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module