Suppose we have three values n, total, and k. Now consider a list of size n whose sum is same as total and where the absolute difference between any two consecutive elements is at most 1. We have to find the maximum value at index k of such a list.
So, if the input is like n = 5 total = 15 k = 3, then the output will be 4, because one possible list is like [3,2,3,4,3], maximum element that is found at index 3 is 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(n, total, k): x = 0 while 1: a = k + 1 s = (x + x - a + 1) * a // 2 a = n - k s += (x + x - a + 1) * a // 2 s -= x if s > total: break x += 1 return x - 1 n = 5 total = 15 k = 3 print(solve(n, total, k))
5, 15, 3