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

Given three values n, total, and k, we need to find the maximum value at index k in a list of size n. The list must satisfy two conditions: its sum equals total, and the absolute difference between consecutive elements is at most 1.

So, if the input is like n = 5, total = 15, k = 3, then the output will be 4, because one possible list is [3, 2, 3, 4, 3], where the maximum element at index 3 is 4.

Algorithm Steps

To solve this, we will follow these steps ?

  • Initialize x := 0
  • Repeat the following steps:
    • Calculate a := k + 1
    • Calculate s := (x + x - a + 1) * floor of a/2
    • Update a := n - k
    • Update s := s + (x + x - a + 1) * floor of a/2
    • Subtract x from s: s := s - x
    • if s > total, then break from loop
    • Increment x := x + 1
  • return x - 1

Implementation

Let us see the following implementation to get better understanding ?

def solve(n, total, k):
    x = 0
    while True:
        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))

The output of the above code is ?

4

How It Works

The algorithm works by iteratively increasing the value x and checking if it's possible to construct a valid list with maximum value x at index k. The formula calculates the minimum sum needed for such a list by considering the constraints on consecutive element differences.

Example Walkthrough

For n = 5, total = 15, k = 3:

def solve_with_trace(n, total, k):
    x = 0
    print(f"Finding maximum value at index {k} for list of size {n} with sum {total}")
    
    while True:
        a = k + 1
        s = (x + x - a + 1) * a // 2
        a = n - k
        s += (x + x - a + 1) * a // 2
        s -= x
        
        print(f"Testing x = {x}: minimum sum needed = {s}")
        
        if s > total:
            break
        x += 1
    
    return x - 1

result = solve_with_trace(5, 15, 3)
print(f"Maximum value at index 3: {result}")
Finding maximum value at index 3 for list of size 5 with sum 15
Testing x = 0: minimum sum needed = -3
Testing x = 1: minimum sum needed = 2
Testing x = 2: minimum sum needed = 7
Testing x = 3: minimum sum needed = 12
Testing x = 4: minimum sum needed = 17
Maximum value at index 3: 3

Conclusion

This algorithm efficiently finds the maximum possible value at a given index by calculating the minimum sum required for each candidate value. The solution uses binary search-like logic to determine the optimal value while respecting the consecutive difference constraint.

Updated on: 2026-03-26T17:32:17+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements