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
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)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code