Skip to content

Commit b266317

Browse files
committed
feat: 1648. Sell Diminishing-Valued Colored Balls : 二分
1 parent ba3f515 commit b266317

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} inventory
3+
* @param {number} orders
4+
* @return {number}
5+
*/
6+
const maxProfit = function (inventory, orders) {
7+
// >= mid 以上的都被售出
8+
let l = 1; let r = 1e9
9+
while (l < r) {
10+
const mid = l + r + 1 >> 1
11+
if (valid(mid)) l = mid
12+
else r = mid - 1
13+
}
14+
function valid (m) {
15+
let o = 0
16+
for (const p of inventory) {
17+
if (p >= m) o += (p - m + 1)
18+
}
19+
return o >= orders
20+
}
21+
let sum = 0n; let rest = orders
22+
// l+1 先全部都选了再说
23+
for (const p of inventory) {
24+
if (p >= l + 1) {
25+
const c = p - (l + 1) + 1
26+
sum += BigInt(p + l + 1) * BigInt(c) / 2n
27+
sum %= BigInt(1e9 + 7)
28+
rest -= c
29+
}
30+
}
31+
// 不够的全部都选 l
32+
sum += BigInt(rest) * BigInt(l)
33+
sum %= BigInt(1e9 + 7)
34+
return sum
35+
}

leetcode/残酷刷题/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
- 1802. Maximum Value at a Given Index in a Bounded Array
144144
- 1201. Ugly Number III.js
145145
- 二分 + 容斥原理 + lcm
146+
- 1648. Sell Diminishing-Valued Colored Balls
146147

147148
### 并查集
148149

0 commit comments

Comments
 (0)