Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?

Given a list of numbers, we need to find a pair (i, j) where i < j such that nums[i] + nums[j] + (i - j) is maximized. Since i < j, the term (i - j) will always be negative, so we're essentially looking for nums[i] + nums[j] - (j - i).

For example, if nums = [6, 6, 2, 2, 2, 8], selecting indices i=0 and j=1 (both values are 6) gives us: 6 + 6 + (0 - 1) = 11.

Algorithm Approach

The key insight is to rearrange the expression nums[i] + nums[j] + (i - j) as (nums[i] + i) + (nums[j] - j). We can iterate through the array and keep track of the maximum value of (nums[i] + i) seen so far, then for each position j, calculate the score using the current maximum.

However, the given solution uses a different optimization approach −

  • Track the largest previous element value

  • For each position, decrease the "large" value by 1 (accounting for distance penalty)

  • Update the maximum score and the largest element tracker

Implementation

class Solution:
    def solve(self, nums):
        large = nums[0]
        maxi = 0
        
        for i in range(1, len(nums)):
            large -= 1  # Account for distance penalty
            maxi = max(large + nums[i], maxi)
            large = max(large, nums[i])
        
        return maxi

# Test with example
ob = Solution()
nums = [6, 6, 2, 2, 2, 8]
result = ob.solve(nums)
print(f"Maximum score: {result}")
Maximum score: 11

How It Works

Let's trace through the example [6, 6, 2, 2, 2, 8]

  • Start: large = 6, maxi = 0

  • i=1: large = 5, maxi = max(5+6, 0) = 11, large = max(5, 6) = 6

  • i=2: large = 5, maxi = max(5+2, 11) = 11, large = max(5, 2) = 5

  • i=3: large = 4, maxi = max(4+2, 11) = 11, large = max(4, 2) = 4

  • i=4: large = 3, maxi = max(3+2, 11) = 11, large = max(3, 2) = 3

  • i=5: large = 2, maxi = max(2+8, 11) = 11, large = max(2, 8) = 8

Alternative Direct Approach

def find_max_score_direct(nums):
    max_score = 0
    
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            score = nums[i] + nums[j] + (i - j)
            max_score = max(max_score, score)
    
    return max_score

# Test with the same example
nums = [6, 6, 2, 2, 2, 8]
result = find_max_score_direct(nums)
print(f"Maximum score (direct): {result}")
Maximum score (direct): 11

Complexity Analysis

Approach Time Complexity Space Complexity
Optimized Solution O(n) O(1)
Direct Approach O(n²) O(1)

Conclusion

The optimized solution efficiently finds the maximum score in O(n) time by tracking the best previous element and accounting for distance penalties. The key insight is maintaining the "large" variable that represents the maximum contribution from previous elements adjusted for distance.

Updated on: 2026-03-25T12:14:05+05:30

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements