3026. Maximum Good Subarray Sum Medium
1/**
2 * [3026] Maximum Good Subarray Sum
3 *
4 * You are given an array nums of length n and a positive integer k.
5 * A <span data-keyword="subarray-nonempty">subarray</span> 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.
6 * Return the maximum sum of a good subarray of nums. If there are no good subarrays, return 0.
7 *
8 * <strong class="example">Example 1:
9 *
10 * Input: nums = [1,2,3,4,5,6], k = 1
11 * Output: 11
12 * Explanation: The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> 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].
13 *
14 * <strong class="example">Example 2:
15 *
16 * Input: nums = [-1,3,2,4,5], k = 3
17 * Output: 11
18 * Explanation: The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> 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].
19 *
20 * <strong class="example">Example 3:
21 *
22 * Input: nums = [-1,-2,-3,-4], k = 2
23 * Output: -6
24 * Explanation: The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> 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].
25 *
26 *
27 * Constraints:
28 *
29 * 2 <= nums.length <= 10^5
30 * -10^9 <= nums[i] <= 10^9
31 * 1 <= k <= 10^9
32 *
33 */
34pub struct Solution {}
35
36// problem: https://leetcode.com/problems/maximum-good-subarray-sum/
37// discuss: https://leetcode.com/problems/maximum-good-subarray-sum/discuss/?currentPage=1&orderBy=most_votes&query=
38
39// submission codes start here
40
41impl Solution {
42 pub fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
43
44 }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_3026() {
55 }
56}
57
Back
© 2025 bowen.ge All Rights Reserved.