-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path095-amicable-chains.js
More file actions
81 lines (66 loc) · 1.59 KB
/
095-amicable-chains.js
File metadata and controls
81 lines (66 loc) · 1.59 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
/**
* Amicable Chains
* Time Complexity: O(N log N)
* Space Complexity: O(N)
*/
function processData(input) {
const N = Number(input.trim());
const divSum = new Array(N + 1).fill(1);
divSum[0] = 0;
divSum[1] = 0;
for (let i = 2; i <= N / 2; i++) {
for (let j = i * 2; j <= N; j += i) {
divSum[j] += i;
}
}
const visited = new Array(N + 1).fill(false);
let bestLen = 0;
let bestMin = 0;
for (let i = 2; i <= N; i++) {
if (visited[i]) continue;
let curr = i;
const map = new Map();
let step = 0;
while (curr <= N && curr > 0 && !map.has(curr)) {
map.set(curr, step++);
curr = divSum[curr];
}
if (map.has(curr)) {
const start = map.get(curr);
const chain = [];
for (const [k, v] of map.entries()) {
if (v >= start) chain.push(k);
}
let valid = true;
for (const x of chain) {
if (x > N) {
valid = false;
break;
}
}
if (valid) {
if (chain.length > bestLen) {
bestLen = chain.length;
bestMin = Math.min(...chain);
} else if (chain.length === bestLen) {
bestMin = Math.min(bestMin, Math.min(...chain));
}
}
}
curr = i;
while (curr <= N && curr > 0 && !visited[curr]) {
visited[curr] = true;
curr = divSum[curr];
}
}
console.log(bestMin.toString());
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});