Leetcode 3026: Maximum Good Subarray Sum

grid47
grid47
Exploring patterns and algorithms
Jan 9, 2024 6 min read

You are given an array nums of length n and a positive integer k. A subarray is called good if the absolute difference between its first and last element is exactly k. The task is to return the maximum sum of any good subarray of nums. If no such subarray exists, return 0.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `nums` of integers and a positive integer `k`.
Example: nums = [5, 7, 1, 9, 3], k = 4
Constraints:
• 2 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
• 1 <= k <= 10^9
Output: Return the maximum sum of any good subarray in `nums` where the absolute difference between the first and last element is exactly `k`. If no good subarray exists, return 0.
Example: Output: 16
Constraints:
Goal: The goal is to find the maximum sum of a subarray where the absolute difference between the first and last element is exactly `k`.
Steps:
• Initialize a variable `ans` to store the maximum sum.
• Use a map to store the last occurrence index of each element.
• Use prefix sum to track cumulative sums while checking for good subarrays.
• For each element, check if the absolute difference between the first and last element is equal to `k`, then compute the sum of that subarray and update `ans`.
Goal: The array `nums` contains integers between `-10^9` and `10^9`, and its length is between `2` and `10^5`.
Steps:
• 2 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
• 1 <= k <= 10^9
Assumptions:
• The array will always have at least two elements.
Input: Input: nums = [5, 7, 1, 9, 3], k = 4
Explanation: The good subarrays are: [5, 7, 1], [7, 1, 9], and [1, 9, 3]. The maximum subarray sum is 16 for the subarray [7, 1, 9].

Input: Input: nums = [-3, -6, -4, -8], k = 2
Explanation: The good subarrays are: [-3, -6, -4], and [-6, -4, -8]. The maximum subarray sum is -13 for the subarray [-3, -6, -4].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus