1
var maxProfit = function (A, k) {3
let rangesum = (i, j) => {4
(i = BigInt(i)), (j = BigInt(j));5
return (j * (j + 1n)) / 2n - (i * (i + 1n)) / 2n;7
A.unshift(0); //prepend the sentinel 08
A.sort((a, b) => a - b);11
mod = BigInt(1e9 + 7),13
// can use all current levels14
while (k >= (n - i) * (A[i] - A[i - 1]) && i > 0) {16
(result = (result + rangesum(A[i - 1], A[i]) * BigInt(n - i)) % mod),17
(k -= (n - i) * (A[i] - A[i - 1]));20
//can use some of the current levels21
if (k > 0 && k >= n - i) {22
let levels = Math.floor(k / (n - i)); //the levels i can use23
result = (result + BigInt(n - i) * rangesum(A[i] - levels, A[i])) % mod;24
k -= levels * (n - i);27
// can use some of the items OF the first level28
if (k > 0 && k < n - i) result = (result + BigInt(k) * BigInt(A[i])) % mod;29
return Number(result);