leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit d9ee70a4fdca0799186b7923f2d24fc41b281b17
parent 4b640063f1be1c56ae6aed07d3b50e345e518323
Author: Jack Sangdahl <jack@pngu.org>
Date:   Tue,  9 Jun 2026 20:53:17 -0600

3689. maximum total subarray value 1

Diffstat:
Amax_total_subarr_val1.c | 30++++++++++++++++++++++++++++++
Amax_total_subarr_val1.py | 25+++++++++++++++++++++++++
2 files changed, 55 insertions(+), 0 deletions(-)

diff --git a/max_total_subarr_val1.c b/max_total_subarr_val1.c @@ -0,0 +1,30 @@ +// 3689. Maximum Total Subarray Value I +#include "leetcode.h" + +/* + * 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 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. + */ + +long long maxTotalValue(int *nums, int numsSize, int k) { + int min = nums[0], max = nums[0]; + for (int i = 0; i < numsSize; i++) { + min = fmin(min, nums[i]); + max = fmax(max, nums[i]); + } + return (long long)(max - min) * k; +} + +int main() { + int n1[] = {1, 3, 2}, n2[] = {4, 2, 5, 1}; + long long r1 = maxTotalValue(n1, ARRAY_SIZE(n1), 2); + long long r2 = maxTotalValue(n2, ARRAY_SIZE(n2), 3); + printf("%lld\n", r1); + assert(r1 == 4); + printf("%lld\n", r2); + assert(r2 == 12); +} diff --git a/max_total_subarr_val1.py b/max_total_subarr_val1.py @@ -0,0 +1,25 @@ +# 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 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. +""" + + +class Solution: + def maxTotalValue(self, nums: List[int], k: int) -> int: + mn = mx = nums[0] + for i in nums: + mn = min(mn, i) + mx = max(mx, i) + return (mx - mn) * k + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxTotalValue(nums=[1, 3, 2], k=2)) + print(obj.maxTotalValue(nums=[4, 2, 5, 1], k=3))