-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
75 lines (73 loc) · 1.85 KB
/
Solution.ts
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
function maximumScore(nums: number[], k: number): number {
const mod = 10 ** 9 + 7;
const n = nums.length;
const arr: number[][] = Array(n)
.fill(0)
.map(() => Array(3).fill(0));
const left: number[] = Array(n).fill(-1);
const right: number[] = Array(n).fill(n);
for (let i = 0; i < n; ++i) {
arr[i] = [i, primeFactors(nums[i]), nums[i]];
}
const stk: number[] = [];
for (const [i, f, _] of arr) {
while (stk.length && arr[stk.at(-1)!][1] < f) {
stk.pop();
}
if (stk.length) {
left[i] = stk.at(-1)!;
}
stk.push(i);
}
stk.length = 0;
for (let i = n - 1; i >= 0; --i) {
const f = arr[i][1];
while (stk.length && arr[stk.at(-1)!][1] <= f) {
stk.pop();
}
if (stk.length) {
right[i] = stk.at(-1)!;
}
stk.push(i);
}
arr.sort((a, b) => b[2] - a[2]);
let ans = 1n;
for (const [i, _, x] of arr) {
const l = left[i];
const r = right[i];
const cnt = (i - l) * (r - i);
if (cnt <= k) {
ans = (ans * qpow(BigInt(x), cnt, mod)) % BigInt(mod);
k -= cnt;
} else {
ans = (ans * qpow(BigInt(x), k, mod)) % BigInt(mod);
break;
}
}
return Number(ans);
}
function primeFactors(n: number): number {
let i = 2;
const s: Set<number> = new Set();
while (i * i <= n) {
while (n % i === 0) {
s.add(i);
n = Math.floor(n / i);
}
++i;
}
if (n > 1) {
s.add(n);
}
return s.size;
}
function qpow(a: bigint, n: number, mod: number): bigint {
let ans = 1n;
for (; n; n >>>= 1) {
if (n & 1) {
ans = (ans * a) % BigInt(mod);
}
a = (a * a) % BigInt(mod);
}
return ans;
}