How to Find the Maximum Element in a List in C++?

Finding the maximum element in a list is a common operation in programming as it allows us to identify the largest value within a collection of elements. In C++, there are various approaches to achieve this efficiently. In this guide, we'll explore two commonly used methods to find the maximum element in a list along with their implementations, examples, time complexity and auxiliary space requirements.

Example:

Suppose we have a list of integers: [5, 10, 3, 8, 15, 7].

The maximum element in this list is 15.

Using a Loop:

This approach involves iterating through the list and keeping track of the maximum element.

Syntax:

int findMax(const vector<int>& arr) {

int maxElement = arr[0]; // Initialize maxElement with the first element

for (int i = 1; i < arr.size(); ++i) {

if (arr[i] > maxElement) {

maxElement = arr[i]; // Update maxElement if a larger element is found

}

}

return maxElement;

}

Example Code:

#include <iostream>
#include <vector>
using namespace std;

int findMax(const vector<int>& arr) {
    int maxElement = arr[0];
    for (int i = 1; i < arr.size(); ++i) {
        if (arr[i] > maxElement) {
            maxElement = arr[i];
        }
    }
    return maxElement;
}
int main() {
    vector<int> numbers = {5, 10, 3, 8, 15, 7};
    cout << "Maximum element: " << findMax(numbers) << endl;
    return 0;
}

Output :

Maximum element: 15

Time Complexity: O(n)
Auxiliary Space:O(1)

Using the std::max_element Function:

The C++ provides the std::max_element function in the <algorithm> header, which returns an iterator pointing to the maximum element in a range.

Syntax:

int maxElement = *std::max_element(arr.begin(), arr.end());

Example Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {5, 10, 3, 8, 15, 7};
    int maxElement = *std::max_element(numbers.begin(), numbers.end());
    cout << "Maximum element: " << maxElement << endl;
    return 0;
}

Output :

Maximum element: 15

Time Complexity: O(n)
Auxiliary Space:O(1)

Post a Comment

Previous Post Next Post