Program to find largest kth index value of one list in Python


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 −

  • x := 0
  • do the following repeatedly, do
    • a := k + 1
    • s :=(x + x - a + 1) * floor if a/2
    • a := n - k
    • s := s +(x + x - a + 1) * floor of a/2
    • s := s - x
    • if s > total, then
      • come out from loop
    • x := x + 1
  • return x - 1

Example

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))

Input

5, 15, 3

Output

4

Updated on: 19-Oct-2021

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements