-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path1802. Maximum Value at a Given Index in a Bounded Array
64 lines (58 loc) · 1.54 KB
/
1802. Maximum Value at a Given Index in a Bounded Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public:
long SUM(long n)
{
return n * (n + 1) / 2;
}
int maxValue(int n, int index, int maxSum)
{
auto check = [&](int mid)
{
long sum = 0;
// sum for 0 to index will be counted below
long reqLeft = mid, haveLeft = index + 1;
if (index == 0)
{
sum += mid;
}
else
{
if (haveLeft >= reqLeft)
{
sum += SUM(mid);
sum += haveLeft - reqLeft;
}
else
{
sum += SUM(mid) - SUM(reqLeft - haveLeft);
}
}
// sum for index + 1 to n - 1 will be counted below
if (index != n - 1)
{
long reqRight = reqLeft - 1;
long haveRight = n - index - 1;
if (haveRight >= reqRight)
{
sum += SUM(mid - 1);
sum += haveRight - reqRight;
}
else
{
sum += SUM(mid - 1) - SUM(reqRight - haveRight);
}
}
return sum <= maxSum;
};
long low = 1, high = maxSum, ans = -1;
while (low <= high)
{
long mid = (low + high) / 2;
if (check(mid))
ans = mid, low = mid + 1;
else
high = mid - 1;
}
return ans;
}
};