LeetCode-in-Java

3979. Maximum Valid Pair Sum

Medium

You are given an integer array nums of length n and an integer k.

A pair of indices (i, j) is called valid if:

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:

Thus, the answer is 13.

Example 2:

Input: nums = [5,1,9], k = 1

Output: 14

Explanation:

Constraints:

Solution

public class Solution {
    public int maxValidPairSum(int[] nums, int k) {
        int res = 0;
        int pre = 0;
        int n = nums.length;
        for (int i = 0; i < n - k; i++) {
            pre = Math.max(pre, nums[i]);
            res = Math.max(res, pre + nums[i + k]);
        }
        return res;
    }
}