Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions problems/3689-maximum-total-subarray-value-i/analysis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# 3689. Maximum Total Subarray Value I

[LeetCode Link](https://leetcode.com/problems/maximum-total-subarray-value-i/)

Difficulty: Medium
Topics: Array, Greedy
Acceptance Rate: 67.9%

## Hints

### Hint 1

Notice the unusual freedom in this problem: subarrays may overlap **and** you can pick the exact same subarray more than once. Whenever a problem lets you reuse the same choice repeatedly, ask yourself: "What is the single best choice, and what stops me from just taking it every time?"

### Hint 2

Think about what bounds the **value** of a subarray, `max - min`. For any subarray `nums[l..r]`, its maximum can never exceed the maximum of the whole array, and its minimum can never go below the minimum of the whole array. So how large can a single subarray's value possibly get, and which subarray achieves that bound?

### Hint 3

The whole array `nums[0..n-1]` always contains the global maximum and the global minimum, so its value is exactly `max(nums) - min(nums)` — and no subarray can beat that. Since you must pick exactly `k` subarrays and you are allowed to repeat, the optimal move is to pick that single best subarray all `k` times. The answer is simply `k * (max(nums) - min(nums))`.

## Approach

This problem looks intimidating because of the "choose `k` subarrays" framing, but the constraints hide a one-line greedy result.

Step 1 — Bound a single subarray's value. For any subarray, `max(subarray) <= max(nums)` and `min(subarray) >= min(nums)`. Therefore:

```
value(subarray) = max(subarray) - min(subarray) <= max(nums) - min(nums)
```

Step 2 — Show the bound is attainable. The full array is itself a valid subarray, and it contains both the global max and the global min, so its value equals exactly `max(nums) - min(nums)`. No subarray can do better.

Step 3 — Use repetition. We must choose exactly `k` subarrays, overlaps are allowed, and duplicates are allowed. Since every chosen subarray contributes at most `max(nums) - min(nums)`, the best total is achieved by choosing the full array (or any subarray spanning both extremes) all `k` times:

```
answer = k * (max(nums) - min(nums))
```

Let's verify with the examples:

- `nums = [1,3,2], k = 2`: max = 3, min = 1, diff = 2, answer = `2 * 2 = 4`. ✅
- `nums = [4,2,5,1], k = 3`: max = 5, min = 1, diff = 4, answer = `3 * 4 = 12`. ✅

So the algorithm is: scan once to find the global maximum and minimum, then multiply their difference by `k`. The hard part is the realization, not the coding — be honest with yourself about whether you saw *why* the whole array dominates every other choice.

A subtle but important detail: `k` can be up to `10^5` and the difference up to `10^9`, so the product can reach `10^14`. That overflows 32-bit integers, so make sure the result is computed in 64-bit arithmetic.

## Complexity Analysis

Time Complexity: O(n) — a single pass to find the minimum and maximum.
Space Complexity: O(1) — only a couple of scalar variables.

## Edge Cases

- **Single element array (`n == 1`)**: max equals min, so the difference is 0 and the answer is 0 regardless of `k`. The greedy formula handles this naturally.
- **All equal elements**: every subarray has value 0, so the total is 0. Again handled automatically.
- **Large `k` and large values**: the product `k * (max - min)` can exceed the 32-bit integer range, so the computation must use 64-bit integers to avoid overflow.
- **`nums[i] = 0`**: zeros are valid; the minimum may legitimately be 0, which is fine.
73 changes: 73 additions & 0 deletions problems/3689-maximum-total-subarray-value-i/problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
number: "3689"
frontend_id: "3689"
title: "Maximum Total Subarray Value I"
slug: "maximum-total-subarray-value-i"
difficulty: "Medium"
topics:
- "Array"
- "Greedy"
acceptance_rate: 6787.1
is_premium: false
created_at: "2026-06-09T04:43:36.205822+00:00"
fetched_at: "2026-06-09T04:43:36.205822+00:00"
link: "https://leetcode.com/problems/maximum-total-subarray-value-i/"
date: "2026-06-09"
---

# 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.



**Example 1:**

**Input:** nums = [1,3,2], k = 2

**Output:** 4

**Explanation:**

One optimal approach is:

* Choose `nums[0..1] = [1, 3]`. The maximum is 3 and the minimum is 1, giving a value of `3 - 1 = 2`.
* Choose `nums[0..2] = [1, 3, 2]`. The maximum is still 3 and the minimum is still 1, so the value is also `3 - 1 = 2`.



Adding these gives `2 + 2 = 4`.

**Example 2:**

**Input:** nums = [4,2,5,1], k = 3

**Output:** 12

**Explanation:**

One optimal approach is:

* Choose `nums[0..3] = [4, 2, 5, 1]`. The maximum is 5 and the minimum is 1, giving a value of `5 - 1 = 4`.
* Choose `nums[0..3] = [4, 2, 5, 1]`. The maximum is 5 and the minimum is 1, so the value is also `4`.
* Choose `nums[2..3] = [5, 1]`. The maximum is 5 and the minimum is 1, so the value is again `4`.



Adding these gives `4 + 4 + 4 = 12`.



**Constraints:**

* `1 <= n == nums.length <= 5 * 10​​​​​​​4`
* `0 <= nums[i] <= 109`
* `1 <= k <= 105`
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

// Maximum Total Subarray Value I
//
// The value of any subarray is max(subarray) - min(subarray), which can never
// exceed max(nums) - min(nums). The full array attains that bound, and since we
// may choose the same subarray repeatedly, the best total is to pick that single
// best subarray all k times. Thus the answer is k * (max(nums) - min(nums)).
//
// We use int64 for the result because k (up to 1e5) times the difference (up to
// 1e9) can reach 1e14, which overflows 32-bit integers.
//
// Time: O(n), Space: O(1).
func maxTotalValue(nums []int, k int) int64 {
mn, mx := nums[0], nums[0]
for _, v := range nums {
if v < mn {
mn = v
}
if v > mx {
mx = v
}
}
return int64(k) * int64(mx-mn)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

import "testing"

func TestMaxTotalValue(t *testing.T) {
tests := []struct {
name string
nums []int
k int
expected int64
}{
{"example 1: [1,3,2] k=2", []int{1, 3, 2}, 2, 4},
{"example 2: [4,2,5,1] k=3", []int{4, 2, 5, 1}, 3, 12},
{"edge case: single element", []int{7}, 5, 0},
{"edge case: all equal elements", []int{3, 3, 3, 3}, 4, 0},
{"edge case: k=1 takes whole-array span", []int{10, 0, 5}, 1, 10},
{"edge case: large product needs int64", []int{0, 1000000000}, 100000, 100000000000000},
{"edge case: contains zero as min", []int{0, 2, 9, 4}, 3, 27},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := maxTotalValue(tt.nums, tt.k)
if result != tt.expected {
t.Errorf("maxTotalValue(%v, %d) = %d, want %d", tt.nums, tt.k, result, tt.expected)
}
})
}
}