[LeetCode] Maximum Total Subarray Value I

3689. Maximum Total Subarray Value I

You are given an integer array nums of length n and an integer k.

You need to choose exactly k non-empty subarrays nums[l..r] of nums. Subarrays may overlap, and the exact same subarray (same l and r) can be chosen more than once.

The value of a subarray nums[l..r] is defined as: max(nums[l..r]) - min(nums[l..r]).

The total value is the sum of the values of all chosen subarrays.

Return the maximum possible total value you can achieve.

1
2
3
4
5
6
class Solution {
public:
long long maxTotalValue(vector<int>& nums, long long k) {
return k * (*max_element(begin(nums), end(nums)) - *min_element(begin(nums), end(nums)));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/11/PS/LeetCode/maximum-total-subarray-value-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.