Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [1,2,3,4,5,6], k = 1 Output: 11 Explanation: The absolute difference between the first and last element must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
Example 2:
Input: nums = [-1,3,2,4,5], k = 3 Output: 11 Explanation: The absolute difference between the first and last element must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
Example 3:
Input: nums = [-1,-2,-3,-4], k = 2 Output: -6 Explanation: The absolute difference between the first and last element must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
Constraints:
2 <= nums.length <= 105-109 <= nums[i] <= 1091 <= k <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[1,2,3,4,5,6] 1
[-1,3,2,4,5] 3
[-1,-2,-3,-4] 2
maximum-subarray)maximum-sum-of-distinct-subarrays-with-length-k)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
Map<Integer, Long> p = new HashMap<>();
p.put(nums[0], 0L);
long s = 0;
int n = nums.length;
long ans = Long.MIN_VALUE;
for (int i = 0; i < n; ++i) {
s += nums[i];
if (p.containsKey(nums[i] - k)) {
ans = Math.max(ans, s - p.get(nums[i] - k));
}
if (p.containsKey(nums[i] + k)) {
ans = Math.max(ans, s - p.get(nums[i] + k));
}
if (i + 1 < n && (!p.containsKey(nums[i + 1]) || p.get(nums[i + 1]) > s)) {
p.put(nums[i + 1], s);
}
}
return ans == Long.MIN_VALUE ? 0 : ans;
}
}
// Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
func maximumSubarraySum(nums []int, k int) int64 {
p := map[int]int64{nums[0]: 0}
var s int64 = 0
n := len(nums)
var ans int64 = math.MinInt64
for i, x := range nums {
s += int64(x)
if t, ok := p[nums[i]-k]; ok {
ans = max(ans, s-t)
}
if t, ok := p[nums[i]+k]; ok {
ans = max(ans, s-t)
}
if i+1 == n {
break
}
if t, ok := p[nums[i+1]]; !ok || s < t {
p[nums[i+1]] = s
}
}
if ans == math.MinInt64 {
return 0
}
return ans
}
# Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
ans = -inf
p = {nums[0]: 0}
s, n = 0, len(nums)
for i, x in enumerate(nums):
s += x
if x - k in p:
ans = max(ans, s - p[x - k])
if x + k in p:
ans = max(ans, s - p[x + k])
if i + 1 < n and (nums[i + 1] not in p or p[nums[i + 1]] > s):
p[nums[i + 1]] = s
return 0 if ans == -inf else ans
// Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
// class Solution {
// public long maximumSubarraySum(int[] nums, int k) {
// Map<Integer, Long> p = new HashMap<>();
// p.put(nums[0], 0L);
// long s = 0;
// int n = nums.length;
// long ans = Long.MIN_VALUE;
// for (int i = 0; i < n; ++i) {
// s += nums[i];
// if (p.containsKey(nums[i] - k)) {
// ans = Math.max(ans, s - p.get(nums[i] - k));
// }
// if (p.containsKey(nums[i] + k)) {
// ans = Math.max(ans, s - p.get(nums[i] + k));
// }
// if (i + 1 < n && (!p.containsKey(nums[i + 1]) || p.get(nums[i + 1]) > s)) {
// p.put(nums[i + 1], s);
// }
// }
// return ans == Long.MIN_VALUE ? 0 : ans;
// }
// }
// Accepted solution for LeetCode #3026: Maximum Good Subarray Sum
function maximumSubarraySum(nums: number[], k: number): number {
const p: Map<number, number> = new Map();
p.set(nums[0], 0);
let ans: number = -Infinity;
let s: number = 0;
const n: number = nums.length;
for (let i = 0; i < n; ++i) {
s += nums[i];
if (p.has(nums[i] - k)) {
ans = Math.max(ans, s - p.get(nums[i] - k)!);
}
if (p.has(nums[i] + k)) {
ans = Math.max(ans, s - p.get(nums[i] + k)!);
}
if (i + 1 < n && (!p.has(nums[i + 1]) || p.get(nums[i + 1])! > s)) {
p.set(nums[i + 1], s);
}
}
return ans === -Infinity ? 0 : ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.