Maximum Good Subarray Sum

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

A subarray of nums is called good if the absolute difference between its first and last element is exactly k. In other words, the subarray nums[i..j] is good if |nums[i] - nums[j]| == k.

Return the maximum sum of a good subarray of nums. If there are no good subarrays, return 0.

Example 1
Inputnums = [1,2,3,4,5,6], k = 1
Output11
The good subarrays are [1,2], [2,3], [3,4], [4,5], and [5,6], and the maximum sum is 11 for [5,6].
Example 2
Inputnums = [-1,3,2,4,5], k = 3
Output11
The good subarrays are [-1,3,2] and [2,4,5], and the maximum sum is 11 for [2,4,5].

Constraints

  • 2 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= 10^9

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate