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 [-3,-4] where |-3-(-4)|=1≠2, actually [-1,-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
Maximum Good Subarray SumInput Array:123456k = 1Good subarrayCheck: |nums[4] - nums[5]| = |5 - 6| = 1 = k ✓Sum of subarray [5,6] = 5 + 6 = 11Other good subarrays: [1,2] sum=3, [2,3] sum=5, [3,4] sum=7, [4,5] sum=9Maximum Sum: 11
Understanding the Visualization
1
Input
Array [1,2,3,4,5,6] and k=1
2
Find Good Subarrays
Check all subarrays where |first-last|=k
3
Output
Return maximum sum among good subarrays
Key Takeaway
🎯 Key Insight: Use hash map to efficiently find matching start/end pairs that differ by exactly k
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen