2023-06-10 21:58:32 +02:00
|
|
|
#include <cassert>
|
|
|
|
|
|
|
|
namespace {
|
2024-01-03 12:06:42 +01:00
|
|
|
long sum(long index, long value, long n) {
|
2023-06-10 21:58:32 +02:00
|
|
|
long count = 0;
|
|
|
|
|
|
|
|
if (value > index) {
|
|
|
|
count += (2 * value - index) * (index + 1) / 2;
|
|
|
|
} else {
|
|
|
|
count += (value + 1) * value / 2 + index - value + 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value >= n - index) {
|
|
|
|
count += (2 * value - n + 1 + index) * (n - index) / 2;
|
|
|
|
} else {
|
|
|
|
count += (value + 1) * value / 2 + n - index - value;
|
|
|
|
}
|
|
|
|
|
|
|
|
return count - value;
|
|
|
|
}
|
2024-01-03 12:06:42 +01:00
|
|
|
} // namespace
|
2023-06-10 21:58:32 +02:00
|
|
|
|
|
|
|
class Solution {
|
2024-01-03 12:06:42 +01:00
|
|
|
public:
|
|
|
|
int maxValue(int n, int index, int maxSum) {
|
2023-06-10 21:58:32 +02:00
|
|
|
int left = 1, right = maxSum;
|
|
|
|
|
|
|
|
while (left < right) {
|
|
|
|
int mid = (left + right + 1) / 2;
|
|
|
|
if (sum(index, mid, n) <= maxSum) {
|
|
|
|
left = mid;
|
|
|
|
} else {
|
|
|
|
right = mid - 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return left;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-01-03 12:06:42 +01:00
|
|
|
int main() {
|
2023-06-10 21:58:32 +02:00
|
|
|
Solution s;
|
|
|
|
|
|
|
|
assert(s.maxValue(4, 2, 6) == 2);
|
|
|
|
assert(s.maxValue(6, 1, 10) == 3);
|
|
|
|
|
|
|
|
// regression
|
|
|
|
assert(s.maxValue(6, 2, 931384943) == 155230825);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|