Loading...
You are given an integer array nums and a non-negative integer k.
Consider every contiguous subarray nums[i..j] (both endpoints included, i <= j) whose two endpoint values differ by exactly k: |nums[i] - nums[j]| = k. Note that a single element (i = j) qualifies only when k = 0.
Return the maximum sum over all qualifying subarrays. Every input is guaranteed to contain at least one qualifying subarray. The answer can be negative.
Input: nums = [1,3,2,1,5], k = 2
Output: 11
Explanation: The subarray [3,2,1,5] has endpoints 3 and 5 with |3 - 5| = 2, and its sum 3 + 2 + 1 + 5 = 11 is the largest achievable.
Input: nums = [4,-2,4], k = 0
Output: 6
Explanation: With k = 0 the endpoints must be equal. The full array [4,-2,4] sums to 6, which beats any single element.
Input: nums = [-5,-3,-5], k = 2
Output: -8
Explanation: The qualifying subarrays are [-5,-3] and [-3,-5], each summing to -8. The answer can be negative.
nums.length ≤105nums[i] ≤104Click "Run" to test with sample cases or "Submit" to run all tests.