Skip to content

Latest commit

 

History

History
154 lines (106 loc) · 3.33 KB

File metadata and controls

154 lines (106 loc) · 3.33 KB

Find the Largest Element in an Array

📋 Problem Statement

Given an integer array arr of size n, find and print its largest element.


🚀 Brute-Force Approach

  1. Sort the array in descending order.
  2. 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).

⚡ Optimal Linear Scan

Key Idea

Traverse the array once, keeping track of the maximum seen so far:

  1. Initialize largest = arr[0].

  2. For each arr[i] (i = 1…n–1):

    • If arr[i] > largest, update largest = arr[i].
  3. After the loop, largest holds the maximum.

Why It’s Optimal

  • Time Complexity: O(n) — one pass.
  • Space Complexity: O(1) — only one extra variable.
  • Doesn’t modify the input.

📝 Pseudocode

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

💾 C++ Code (Revised)

#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;
}

📈 Complexity Analysis

Approach Time Complexity Space Complexity Modifies Input?
Sorting O(n log n) O(1) in-place Yes
Linear Scan O(n) O(1) No

✨ Notes & Facts

  • 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.

❓ FAQs

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 largest and smallest and update both — still O(n).