Maximum Good Subarray Sum - Problem

You are given an array nums of length n and a positive integer k. Your task is to find the maximum sum among all "good" subarrays.

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

Goal: Return the maximum sum of a good subarray. If no good subarrays exist, return 0.

Example: For nums = [1, 2, 3, 4, 5] and k = 3, the subarray [1, 2, 3, 4] is good because |1 - 4| = 3, and its sum is 10.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,2,3,4,5,6], k = 1
โ€บ Output: 11
๐Ÿ’ก Note: The subarray [5,6] is good because |5-6| = 1 = k, and has sum 11. Other good subarrays like [1,2] have smaller sums.
example_2.py โ€” Multiple Good Subarrays
$ Input: nums = [-1,3,2,4,5], k = 3
โ€บ Output: 11
๐Ÿ’ก Note: The subarray [2,4,5] is good because |2-5| = 3 = k, and has sum 11. The subarray [-1,3,2] is also good since |-1-2| = 3, but has sum 4.
example_3.py โ€” No Good Subarrays
$ Input: nums = [1,2,3,4], k = 10
โ€บ Output: 0
๐Ÿ’ก Note: No pair of elements has absolute difference of 10, so there are no good subarrays. Return 0.

Constraints

  • 2 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค 109

Visualization

Tap to expand
Hash Map + Prefix Sum VisualizationArray1234Hash Map (Value โ†’ MinPrefix)1 โ†’ 02 โ†’ 13 โ†’ 3Looking for: 4ยฑ1 = {3,5}Found 3! Sum = 10+4-3 = 11Prefix Sum EvolutionIndex 0: prefix = 0, add 1 โ†’ 1Index 1: prefix = 1, add 2 โ†’ 3Index 2: prefix = 3, add 3 โ†’ 6Index 3: prefix = 6, add 4 โ†’ 10Good subarray [3,4]: sum = 10-3 = 7๐Ÿš€ O(n) time, O(n) space - Optimal Solution!
Understanding the Visualization
1
Track Prefix Sums
Maintain running sum and map each value to minimum prefix sum seen
2
Look for Complements
For each element x, check if xยฑk exists in our map
3
Calculate Instantly
Use prefix sum difference to get subarray sum in O(1)
Key Takeaway
๐ŸŽฏ Key Insight: Prefix sums with hash maps transform the problem from checking all pairs O(nยฒ) to single-pass complement lookup O(n)
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
78.2K Views
High Frequency
~18 min Avg. Time
1.8K 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