Maximum Valid Pair Sum Problem
Description
LeetCode Problem 3979.
You are given an integer array nums of length n and an integer k.
A pair of indices (i, j) is called valid if:
0 <= i < j < nj - i >= k
Return the maximum value of nums[i] + nums[j] among all valid pairs.
Example 1:
Input: nums = [1,3,5,2,8], k = 2
Output: 13
Explanation:
The valid pairs are:
- (0, 2): nums[0] + nums[2] = 6
- (0, 3): nums[0] + nums[3] = 3
- (0, 4): nums[0] + nums[4] = 9
- (1, 3): nums[1] + nums[3] = 5
- (1, 4): nums[1] + nums[4] = 11
- (2, 4): nums[2] + nums[4] = 13
Thus, the answer is 13.
Example 2:
Input: nums = [5,1,9], k = 1
Output: 14
Explanation:
- Since k = 1, every pair is valid.
- The maximum value is obtained from a pair (0, 2), which is nums[0] + nums[2] = 5 + 9 = 14.
- Thus, the answer is 14.
Constraints:
2 <= n == nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= n - 1
Solution
Approach: Sliding Window
A pair (i, j) with i < j is valid when j - i >= k, which means i <= j - k. Since k >= 1, this already forces i < j.
Loop over the right index j from k to n - 1. For each j, the allowed left indices are 0 to j - k, and this range grows by one element each step. Keep x, the largest nums[i] in that range, by folding in nums[j - k] at every step. The best pair ending at j is x + nums[j], and the answer is the maximum over all j.
The sum is at most 2 * 109, which still fits in a 32-bit signed integer (its limit is about 2.147 * 109).
Complexity: O(n) time and O(1) space, where n is the length of nums.
class Solution:
def maxValidPairSum(self, nums: List[int], k: int) -> int:
ans = x = 0
for j in range(k, len(nums)):
y = nums[j]
x = max(x, nums[j - k])
ans = max(ans, x + y)
return ans