Given an integer array arr of size n, find and print its largest element.
- Sort the array in descending order.
- Pick the first element (index 0).
// Brute-force via sorting (O(n log n))
void largestBySorting(vector<int>& arr) {
sort(arr.begin(), arr.end(), greater<int>());
cout << arr[0];
}Drawbacks:
- Higher time complexity: O(n log n) just to find one element.
- Modifies the original array (unless you copy).
Traverse the array once, keeping track of the maximum seen so far:
-
Initialize
largest = arr[0]. -
For each
arr[i](i = 1…n–1):- If
arr[i] > largest, updatelargest = arr[i].
- If
-
After the loop,
largestholds the maximum.
- Time Complexity: O(n) — one pass.
- Space Complexity: O(1) — only one extra variable.
- Doesn’t modify the input.
FUNCTION findLargest(arr, n):
IF n == 0:
ERROR "Array is empty"
largest ← arr[0]
FOR i FROM 1 TO n−1:
IF arr[i] > largest:
largest ← arr[i]
RETURN largest
#include <bits/stdc++.h>
using namespace std;
// Finds and returns the largest element in 'arr' of size 'n'.
// Throws an error if the array is empty.
int findLargest(const vector<int>& arr) {
if (arr.empty()) {
throw invalid_argument("Array must contain at least one element.");
}
int largest = arr[0];
for (int x : arr) {
if (x > largest) {
largest = x;
}
}
return largest;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
try {
int result = findLargest(arr);
cout << result << "\n";
} catch (const exception& e) {
cerr << "Error: " << e.what() << "\n";
return 1;
}
return 0;
}| Approach | Time Complexity | Space Complexity | Modifies Input? |
|---|---|---|---|
| Sorting | O(n log n) | O(1) in-place | Yes |
| Linear Scan | O(n) | O(1) | No |
- Edge Case: Empty array → must handle separately (throws an exception above).
- Standard Library:
*max_element(arr.begin(), arr.end())also returns the largest in O(n). - Works with negative and positive integers equally.
- To find the second largest, track both max and second-max in one pass.
Q1: What if all elements are equal?
The algorithm returns that common value — which is correct.
Q2: How to handle very large arrays?
Linear scan is the best: it’s memory-efficient and cache-friendly.
Q3: Can I use recursion to find the max?
Yes, but recursion adds O(log n) or O(n) stack overhead; iterative scan is simpler and safer.
Q4: What if I need both max and min?
In one pass, maintain two variables
largestandsmallestand update both — still O(n).