- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

[3, 4, 2, 2, 4]

5

- Related Questions & Answers
- Find K-th Smallest Pair Distance in C++
- Program to find maximum distance between a pair of values in Python
- Program to find largest distance pair from two list of numbers in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
- Smallest Distance Between Two Words in Python
- Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?
- Program to find maximum size of any sequence of given array where every pair is nice in Python
- Program to find length of the largest subset where one element in every pair is divisible by other in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find kth smallest n length lexicographically smallest string in python
- Python Program to Filter Rows with a specific Pair Sum
- Find required sum pair with JavaScript

Advertisements