Program to find smallest pair sum where distance is not consecutive in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called. Now let us consider any pair of indices (i, j) where i < j and j - i > 1. Then find the smallest pair sum.

So, if the input is like nums = [3, 4, 2, 2, 4], then the output will be 5, we can select values 3 and 2 so the total sum is 5. We cannot select 2 and 2 because they are adjacent, and violating the j - i > 1 constraint.

To solve this, we will follow these steps −

  • n := size of nums
  • min_seen := nums[0]
  • ans := inf
  • for i in range 2 to n - 1, do
    • ans := minimum of ans and (min_seen + nums[i])
    • min_seen := minimum of min_seen and nums[i - 1]
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   n = len(nums)
   min_seen = nums[0]

   ans = float("inf")

   for i in range(2, n):
      ans = min(ans, min_seen + nums[i])

      min_seen = min(min_seen, nums[i - 1])
   return ans

nums = [3, 4, 2, 2, 4]
print(solve(nums))

Input

[3, 4, 2, 2, 4]

Output

5
raja
Published on 14-Oct-2021 10:06:34
Advertisements