Skip to content

Practice Maximum Good Subarray Sum

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#3026
LeetCode Problem

Maximum Good Subarray Sum

Problem Statement

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.

Source: Maximum Good Subarray Sum on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
nums = [1,2,3,4,5,6], k = 1
Output
11

# Example 2

Input
nums = [-1,3,2,4,5], k = 3
Output
11

# Example 3

Input
nums = [-1,-2,-3,-4], k = 2
Output
-6

Constraints

2 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
1 <= k <= 10^9

Related LeetCode Problems

Practice more problems similar to Maximum Good Subarray Sum.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.