-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3rdmax.cpp
More file actions
65 lines (52 loc) · 1.57 KB
/
3rdmax.cpp
File metadata and controls
65 lines (52 loc) · 1.57 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
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
int thirdMaximum(int* arr, int size) {
if (size < 3) {
cout << "Array must have at least 3 elements!" << endl;
return -1; // Indicate error
}
// Initialize the first, second, and third maximum to "very small" values
int firstMax = arr[0], secondMax = arr[0], thirdMax = arr[0];
// Ensure the initial values differ
for (int i = 1; i < size; ++i) {
if (arr[i] < firstMax) {
thirdMax = secondMax = firstMax = arr[i];
break;
}
}
for (int i = 0; i < size; ++i) {
int current = arr[i];
// Update the three maximums
if (current > firstMax) {
thirdMax = secondMax;
secondMax = firstMax;
firstMax = current;
} else if (current > secondMax && current < firstMax) {
thirdMax = secondMax;
secondMax = current;
} else if (current > thirdMax && current < secondMax) {
thirdMax = current;
}
}
return thirdMax;
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
if (n < 3) {
cout << "Array size must be at least 3." << endl;
return 1;
}
// Dynamically allocate memory for the array
int* arr = new int[n];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
int thirdMax = thirdMaximum(arr, n);
cout << "The third maximum value is: " << thirdMax << endl;
// Free the allocated memory
delete[] arr;
return 0;
}