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
Maximum Good Subarray Sum INPUT Array nums: 1 i=0 2 i=1 3 i=2 4 i=3 5 i=4 6 i=5 k = 1 Good Subarray Condition: |nums[i] - nums[j]| == k Valid pairs (diff = 1): (1,2), (2,3), (3,4), (4,5), (5,6) Prefix Sums: [0, 1, 3, 6, 10, 15, 21] ALGORITHM STEPS 1 Build Prefix Sum prefix[i] = sum of nums[0..i-1] 2 HashMap: val -> minPrefix Track min prefix for each value 3 For each nums[i]: Check map[nums[i]+k], map[nums[i]-k] 4 Update max sum sum = prefix[i+1] - minPrefix HashMap State: val | minPrefix 1 | 0 2 | 1 3 | 3 4 | 6 5 | 10 Best: 5+6 = 11 (prefix[6]-prefix[4]) FINAL RESULT Best Good Subarray Found: 1 2 3 4 5 6 nums[4..5] Verification: |nums[4] - nums[5]| = |5-6| = 1 = k [OK] Subarray Sum: 5 + 6 = 11 Output: 11 Key Insight: Use HashMap to store minimum prefix sum for each value. For a good subarray ending at index j, we need the earliest occurrence of (nums[j] + k) or (nums[j] - k) with minimum prefix sum. This gives max subarray sum = prefix[j+1] - minPrefix. Time: O(n), Space: O(n). TutorialsPoint - Maximum Good Subarray Sum | Optimized Hash Map with Min Prefix
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