Maximum Good Subarray Sum - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,4,5,6], k = 1
›
Output:
11
💡 Note:
The good subarray with maximum sum is [5,6] since |5-6|=1=k, and sum=5+6=11
Example 2 — No Good Subarrays
$
Input:
nums = [-1,3,2,4,5], k = 3
›
Output:
11
💡 Note:
Good subarray [2,4,5] where |2-5|=3=k, sum=2+4+5=11
Example 3 — Negative Numbers
$
Input:
nums = [-1,-2,-3,-4], k = 2
›
Output:
-6
💡 Note:
Good subarray [-1,-2,-3] where |(-1)-(-3)|=2=k, sum=-1+(-2)+(-3)=-6
Constraints
- 2 ≤ nums.length ≤ 105
- -109 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code