Skip to content

Commit d739de2

Browse files
authored
Merge pull request #434 from Ankkkitt/branch1
Solution added for max and min element in array
2 parents 45b2ec6 + 98dbb64 commit d739de2

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Arrays/max_and_min_element.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Problem Description:
2+
// Here, we have an array arr[]. The array contains n integer values.
3+
// We have to find the maximum value and minimum value out of all values of the array.
4+
5+
// Let’s take an example to understand the problem
6+
7+
// Input : n = 5
8+
// a[n] = { 10, 20, 30, 40, 50}
9+
10+
// Output : Maximum element of array is 50
11+
// Minimum element of array is 10
12+
13+
// Explanation :
14+
//
15+
// There can be multiple solution for this problem.
16+
// One solution is to directly compare the elements of array. This can be done by using two different approaches :
17+
// 1.Iterative approach
18+
// 2.Recursive approach
19+
20+
// Here we are using iterative approach to solve this problem.
21+
// initially we will set a[0] as min/max. Then we iterate over each elemnts using loop and compare it with max/min element of array.
22+
23+
// Time Complexity : O(n)
24+
// Space Complexity : O(1)
25+
26+
#include <iostream>
27+
using namespace std;
28+
29+
int getmax( int a[], int n){
30+
int max = a[0];
31+
for( int i=1; i<n; i++)
32+
{
33+
if( a[i] > max )
34+
max = a[i];
35+
}
36+
37+
return max;
38+
}
39+
40+
int getmin( int a[], int n){
41+
int min = a[0];
42+
for( int i=1; i<n; i++)
43+
{
44+
if( a[i] < min )
45+
min = a[i];
46+
}
47+
48+
return min;
49+
}
50+
51+
int main()
52+
{
53+
int n;
54+
cin>>n;
55+
int a[n];
56+
for( int i=0; i<n; i++)
57+
{
58+
cin>>a[i];
59+
}
60+
int max = getmax( a, n);
61+
int min = getmin( a, n);
62+
cout<<"Maximum element of array is :"<<max<<endl;
63+
cout<<"Minimum element of array is :"<<min<<endl;
64+
65+
}
66+
67+

0 commit comments

Comments
 (0)