Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

how
find
maximum
element
array

How to find the maximum element in an array

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

An array stores data. The data can be of any type, and each element represents a specific piece of information.

Algorithm

Suppose there is a team of five players, ​and the oldest player is going to become the captain.

  1. The array that stores the age of all the players will be traversed to find the maximum age.

  2. A variable named (max) that stores the maximum element found so far will be initialized.

  3. Initially, the first element will be set as the max and then the array will be traversed.

  4. Each element will be compared with the max, and if the current element is greater than the max, the max will be set to the current element.

  5. Finally, the max is returned.

The following slides better explain this problem:

1 of 7

Code

The following codes find the outputs and maximum element in the array:

#include <iostream>
using namespace std;
int largest(int arr[], int n)
{
int i;
// Initialize maximum element
int max = arr[0];
// Traverse array elements
// and compare every element with current max
for (i = 1; i < n; i++)
if (arr[i] > max)
{
max = arr[i];
}
return max;
}
// Driver Code
int main()
{
int arr[] = {18, 24, 21, 27, 19};// ages of players
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum element is "
<< largest(arr, n);
return 0;
}

RELATED TAGS

how
find
maximum
element
array
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring