LeetCode in Kotlin

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

import kotlin.math.max

class Solution {
    fun maxValidPairSum(nums: IntArray, k: Int): Int {
        var res = 0
        var pre = 0
        val n = nums.size
        for (i in 0..<n - k) {
            pre = max(pre, nums[i])
            res = max(res, pre + nums[i + k])
        }
        return res
    }
}