The Maximum Good Subarray Sum coding problem defines a "good" subarray as one where the absolute difference between the first and last elements is exactly 1. Given an array of integers, you need to find the maximum possible sum of any such good subarray. This combines subarray sum optimization with a structural constraint on the endpoints, making it a layered problem that tests both prefix sum knowledge and hash table usage.
Companies like Google, Amazon, Zepto, Groww, and Atlassian favor this problem because it tests the ability to add constraints on top of a classical problem (maximum subarray sum). Pure dynamic programming won't work directly because of the endpoint condition. Candidates who can reformulate the problem using prefix sums and hash maps demonstrate the ability to adapt known techniques to novel constraints.
The solution uses prefix sums with a hash table. Compute prefix sums as you iterate. For each index j, you want the minimum prefix sum at some index i where nums[i] and nums[j] differ by exactly 1, and i ≤ j. You maintain a hash map from each value to the minimum prefix sum seen at an index with that value. For each j, check the hash map for value nums[j]-1 and nums[j]+1, and compute the candidate sum as prefix[j] - minPrefix[neighbor]. Update the answer and update the hash map for nums[j].
Array: [1, 2, 1, 3]
The good subarray [2, 1, 3] has first=2, last=3, |2-3|=1, sum=6.
nums[j]-1 but not nums[j]+1 misses valid good subarrays.nums[j] before checking it can incorrectly create subarrays of length 0.For the Array Hash Table Prefix Sum interview pattern, practice thinking of subarray sum problems as "prefix[j] - prefix[i]" and ask what constraint on index i you can look up in a hash map. This reformulation converts many constrained subarray problems into O(n) solutions. The "good subarray" endpoint condition maps naturally to hash map lookups by value.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count of Interesting Subarrays | Medium | Solve | |
| Maximum Size Subarray Sum Equals k | Medium | Solve | |
| Make Sum Divisible by P | Medium | Solve | |
| Maximum Subarray Sum With Length Divisible by K | Medium | Solve | |
| Stable Subarrays With Equal Boundary and Interior Sum | Medium | Solve |