-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_min_max.cpp
More file actions
55 lines (42 loc) · 1.07 KB
/
find_min_max.cpp
File metadata and controls
55 lines (42 loc) · 1.07 KB
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
//
// Created by Mayank Parasar on 2020-01-31.
//
/*
* Given a list of numbers of size n, where n is greater than 3,
* find the maximum and minimum of the list using less than 2 * (n - 1) comparisons.
* def find_min_max(nums):
# Fill this in.
print find_min_max([3, 5, 1, 2, 4, 8])
# (1, 8)
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int> find_min_max(vector<int>& arr) {
int num_comparisions = 0;
int min = arr[0];
int max = arr[0];
for(int ii = 0; ii < arr.size(); ii++) {
if(arr[ii] > max) {
max = arr[ii];
num_comparisions++;
}
else if(arr[ii] < min) {
min = arr[ii];
num_comparisions++;
}
}
cout << num_comparisions;
vector<int> min_max;
min_max.push_back(min);
min_max.push_back(max);
return min_max;
}
int main() {
vector<int> arr = {3, 5, 1, 2, 4, 8};
vector<int> min_max = find_min_max(arr);
cout << endl;
cout << "min: " << min_max[0] << endl;
cout << "max: " << min_max[1] << endl;
return 0;
}