1
var maxProfit = function (A, k) {
2
//rangeSum Formula
3
let rangesum = (i, j) => {
4
(i = BigInt(i)), (j = BigInt(j));
5
return (j * (j + 1n)) / 2n - (i * (i + 1n)) / 2n;
6
};
7
A.unshift(0); //prepend the sentinel 0
8
A.sort((a, b) => a - b);
9
let n = A.length,
10
result = 0n,
11
mod = BigInt(1e9 + 7),
12
i = n - 1;
13
// can use all current levels
14
while (k >= (n - i) * (A[i] - A[i - 1]) && i > 0) {
15
if (A[i] != A[i - 1])
16
(result = (result + rangesum(A[i - 1], A[i]) * BigInt(n - i)) % mod),
17
(k -= (n - i) * (A[i] - A[i - 1]));
18
i--;
19
}
20
//can use some of the current levels
21
if (k > 0 && k >= n - i) {
22
let levels = Math.floor(k / (n - i)); //the levels i can use
23
result = (result + BigInt(n - i) * rangesum(A[i] - levels, A[i])) % mod;
24
k -= levels * (n - i);
25
A[i] -= levels;
26
}
27
// can use some of the items OF the first level
28
if (k > 0 && k < n - i) result = (result + BigInt(k) * BigInt(A[i])) % mod;
29
return Number(result);
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0