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; } }
|