LC.P1802[有界数组中指定下标处的最大值]

方法一:贪心+二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int maxValue(int n, int index, int maxSum) {
int left = 1, right = maxSum;
while (left < right) {
int mid = left + right + 1 >> 1;
if (sum(mid - 1, index) + sum(mid, n - index) <= maxSum) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}

private long sum(long x, int cnt) {
return x >= cnt ? (x + x - cnt + 1) * cnt / 2 : (1 + x) * x / 2 + cnt - x;
}
}
  • 时间复杂度:$O(logM)$,其中$M = maxSum$
  • 空间复杂度:$O(1)$