forked from ttzztztz/leetcodeAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1316. Luck Number.cpp
More file actions
44 lines (37 loc) · 1.1 KB
/
1316. Luck Number.cpp
File metadata and controls
44 lines (37 loc) · 1.1 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
class Solution {
public:
/**
* @param arr: the arr
* @return: the sum of the luck number
*/
int luckNumber(vector<int> &arr) {
int answer = 0;
const int N = arr.size();
vector<int> f(N), g(N);
vector<bool> existF(N, false), existG(N, false);
set<int> left;
for (int i = 0; i < N; i++) {
auto it = left.upper_bound(arr[i]);
if (it != left.end()) {
existF[i] = true;
f[i] = *it;
}
left.insert(arr[i]);
}
set<int> right;
for (int i = N - 1; i >= 0; i--) {
auto it = right.lower_bound(arr[i]);
if (i != N - 1 && it != right.begin()) {
it--;
existG[i] = true;
g[i] = *it;
}
right.insert(arr[i]);
}
for (int i = 1; i < N - 1; i++) {
if (!existF[i] || !existG[i]) continue;
if (f[i] % g[i] == 0) answer++;
}
return answer;
}
};