
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Advertisements