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:
0 <= i < j < nj - i >= kReturn 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] = 13Thus, the answer is 13.
Example 2:
Input: nums = [5,1,9], k = 1
Output: 14
Explanation:
k = 1, every pair is valid.(0, 2), which is nums[0] + nums[2] = 5 + 9 = 14.Constraints:
2 <= n == nums.length <= 1051 <= nums[i] <= 1091 <= k <= n - 1public 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;
}
}