Maximum sum of a subarray whose ends differ by k
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Apr 2026. It tests prefix sums and hash maps.
Given an integer array nums and an integer k, a contiguous subarray nums[l..r] is good when its first and last elements differ by exactly k: abs(nums[l] - nums[r]) == k. Return the largest sum of a good subarray, or 0 if there is none.
Interface
Unless you agree on a different interface with the interviewer, assume:
max_good_subarray_sum(nums: list[int], k: int) -> int
When k == 0, a single element is a good subarray (its first and last elements are the same element).
Example
max_good_subarray_sum([1, 2, 3, 4, 5], 3) -> 14 # [2, 3, 4, 5]: |2 - 5| = 3
max_good_subarray_sum([-1, 3, 2, 4, 5], 3) -> 11 # [2, 4, 5]
max_good_subarray_sum([5, 1, 8], 10) -> 0 # no good subarray
max_good_subarray_sum([-5, -2], 3) -> -7 # the only good subarray has a negative sum
Constraints
-
1 <= len(nums) <= 10^5;-10^9 <= nums[i] <= 10^9;0 <= k <= 10^9. - The answer fits in a signed 64-bit integer.
Clarifying questions
- Is the difference absolute?
- If good subarrays exist but all have negative sums, return the best of them or
0? - Is a single element good when
k == 0?
What a strong answer covers
- The sum of
nums[l..r]isprefix[r+1] - prefix[l]. To maximise it for a fixedr, the start should have the smallestprefix[l]among indicesl <= rwhose value isnums[r] - kornums[r] + k. - One left-to-right pass with a hash map from value to the smallest prefix sum seen before an index holding that value. Insert the current index before checking when
k == 0, so the single element counts.O(n)time and space. - Why the brute force over all pairs is
O(n^2)and too slow. - Tests:
k = 0, all-negative arrays, repeated values, no good subarray.
Follow-ups
- Return the indices
(l, r)of the best subarray. - The ends must be equal (
k = 0) and you may use onlyO(1)extra space. - Count the good subarrays instead.
Where it's asked
- Google · Onsite coding · Last asked Apr 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
prefix sums · hash maps
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
