-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmaximum-element.cpp
More file actions
100 lines (84 loc) · 1.87 KB
/
maximum-element.cpp
File metadata and controls
100 lines (84 loc) · 1.87 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Maximum Element
// Given three types of queries, insert an element, delete an element or find the maximum element in a stack.
//
// https://www.hackerrank.com/challenges/maximum-element/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// nota: le challenge garantit que les bornes ne seront jamais dépassées
// ainsi, on ne vérifie rien sur la validité des données en entrée
int stack[100000];
int top = 0;
// Solution 1: naïve
int main_naif()
{
int q;
cin >> q;
while (q--)
{
int op;
cin >> op;
if (op == 1)
{
int x;
cin >> x;
//push
stack[top++] = x;
}
else if (op == 2)
{
//delete
top--;
}
else if (op == 3)
{
//print max
int max = -1;
for (int i = 0; i < top; ++i)
if (stack[i] > max) max = stack[i];
cout << max << endl;
}
}
return 0;
}
// Solution 2: performante
// pas la peine de stacker les éléments, il n'y a que le max qui nous intéresse!
int main()
{
int q;
cin >> q;
while (q--)
{
int op;
cin >> op;
if (op == 1)
{
int x;
cin >> x;
//push
// par défaut le max de la stack est l'élément lu
int m = x;
// s'il y a qqch dans la stack, on vérifie le max
if (top > 0)
{
if (stack[top - 1] > m) m = stack[top - 1];
}
stack[top++] = m;
}
else if (op == 2)
{
//delete
top--;
}
else if (op == 3)
{
//print max
cout << stack[top - 1] << endl;
}
}
return 0;
}