-
Notifications
You must be signed in to change notification settings - Fork 0
/
max-min-recursive.cpp
77 lines (63 loc) · 1.56 KB
/
max-min-recursive.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class MaxMin {
public:
int max;
int min;
MaxMin() {
max = INT_MIN;
min = INT_MAX;
}
// Divide and Conquer Approach of finding max-min of the array
MaxMin findMaxMin(vector<int> &a, int l, int h) {
MaxMin res;
// when array has only one element
if(l==h) {
res.max = res.min = a[l];
}
// when array has two elements
else if(l==h-1) {
if(a[l] < a[h]) {
res.max = a[h];
res.min = a[l];
}
else {
res.max = a[l];
res.min = a[h];
}
}
// when array has more than two elements
else {
int mid = (l+h)/2;
MaxMin x, y;
// divide the array from mid and find max-min of both sub-arrays
x = findMaxMin(a, l, mid);
y = findMaxMin(a, mid+1, h);
// assign the maximum and minimum of both to res
if(x.max > y.max)
res.max = x.max;
else
res.max = y.max;
if(x.min < y.min)
res.min = x.min;
else
res.min = y.min;
}
return res;
}
};
int main() {
int n;
cin>>n;
vector<int> v(n);
for(int i=0; i<n; i++) {
cin>>v[i];
}
MaxMin obj;
obj = obj.findMaxMin(v, 0, n-1);
cout<<"Output : \n";
cout<<"Max : "<<obj.max;
cout<<"\nMin : "<<obj.min;
}