forked from markhary/codility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxCounters.cpp
87 lines (71 loc) · 2.21 KB
/
MaxCounters.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
78
79
80
81
82
83
84
85
86
87
// https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/
//
// Task Score: 55%
// Correctness: 100%
// Performance: 100%
// Detected time complexity: O(N+M)
//
#include <vector>
#include <algorithm>
vector<int> solution(int N, vector<int> &A) {
int M = A.size();
// Initialize counters to 0
std::vector<int> counters(N, 0);
int maximum = 0;
int minimum = 0;
for (int k=0; k<M; k++) {
if (A[k] <= N) {
// if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X)
// and track max counter
int counter = std::max(counters[A[k]-1], minimum) + 1;
counters[A[k]-1] = counter;
if (counter > maximum) {
maximum = counter;
}
} else if (A[k] == (N+1)) {
// if A[K] = N + 1 then operation K is max counter.
// Have to set all elements of counter to max
// Added logic to keep this O(N)
minimum = maximum;
}
}
// Keeping it O(N)
// Go through and set the minimum value of all counters in case they
// have not been updated.
for (int k=0; k<N; k++) {
counters[k] = std::max(counters[k], minimum);
}
return counters;
}
// https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/
//
// Task Score: 100%
// Correctness: 100%
// Performance: 100%
// Detected time complexity: O(N+M)
//
#include <algorithm>
vector<int> solution(int N, vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
auto max = 0;
auto index = 0;
auto last = 0;
std::vector<int> result(N);
std::for_each(A.cbegin(),A.cend(),[&](const int& code){
if(code >= 1 && code <= N){
index = code -1;
if( result[index] < last)
result[index] = last;
++result[index];
if(max < result[index])
max = result[index];
}else if(code == (N + 1)){
last = max;
}
});
std::for_each(result.begin(),result.end(),[last](int& value){
if(value < last)
value = last;
});
return result;
}