Skip to content

Commit 1b5e3d3

Browse files
committed
feat: 1802. Maximum Value at a Given Index in a Bounded Array : 二分查找
1 parent 825cab7 commit 1b5e3d3

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 二分
3+
* @param {number} n
4+
* @param {number} index
5+
* @param {number} maxSum
6+
* @return {number}
7+
*/
8+
const maxValue = function (n, index, maxSum) {
9+
let l = 0; let r = 1e9
10+
while (l < r) {
11+
const mid = l + r + 1 >> 1
12+
if (valid(mid)) l = mid
13+
else r = mid - 1
14+
}
15+
function valid (x) {
16+
let sum = x
17+
// 下标 0~index-1: 分布 1, 1, ..., 1..., x-2, x-1
18+
const leftCnt = Math.min(index, x - 1); const leftRest = index - leftCnt
19+
sum += (x - 1 + x - leftCnt) * leftCnt / 2 + leftRest
20+
const rightCnt = Math.min(n - 1 - index, x - 1); const rightRest = n - 1 - index - rightCnt
21+
sum += (x - 1 + x - rightCnt) * rightCnt / 2 + rightRest
22+
return sum <= maxSum
23+
}
24+
return l
25+
}

leetcode/残酷刷题/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@
140140
- 1235. Maximum Profit in Job Scheduling
141141
- 1751. Maximum Number of Events That Can Be Attended II
142142
- 1300. Sum of Mutated Array Closest to Target
143+
- 1802. Maximum Value at a Given Index in a Bounded Array
143144

144145
### 并查集
145146

0 commit comments

Comments
 (0)