
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find smallest pair sum where distance is not consecutive in Python
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
- Related Articles
- Find K-th Smallest Pair Distance in C++
- Program to find maximum distance between a pair of values in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find largest distance pair from two list of numbers in Python
- Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Program to find size of smallest sublist whose sum at least target 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 kth smallest n length lexicographically smallest string in python
- Program to find length of the largest subset where one element in every pair is divisible by other in Python
- Program to create data structure to check pair sum is same as value in Python
- Program to check three consecutive odds are present or not in Python
- Python Program to Filter Rows with a specific Pair Sum

Advertisements