LeetCode #3691 — HARD

Maximum Total Subarray Value II

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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

You must select exactly k distinct non-empty subarrays nums[l..r] of nums. Subarrays may overlap, but the exact same subarray (same l and r) cannot 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[1..3] = [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 <= min(105, n * (n + 1) / 2)
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums of length n and an integer k. You must select exactly k distinct non-empty subarrays nums[l..r] of nums. Subarrays may overlap, but the exact same subarray (same l and r) cannot 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Greedy · Segment Tree

Example 1

[1,3,2]
2

Example 2

[4,2,5,1]
3
Step 02

Core Insight

What unlocks the optimal approach

  • For fixed <code>l</code>, the sequence <code>v(l,r)=max(nums[l..r])−min(nums[l..r])</code> is non-increasing as <code>r</code> moves left.
  • Build RMQs (sparse tables) for range max/min so each <code>v(l,r)</code> is queryable in <code>O(1)</code>.
  • Use a max-heap with <code>v(l,n-1)</code> for all <code>l</code>; pop the largest <code>k</code> times, and after popping an entry from <code>(l,r)</code> push <code>(l,r-1)</code> if <code>r>l</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3691: Maximum Total Subarray Value II
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3691: Maximum Total Subarray Value II
// package main
// 
// import (
// 	"container/heap"
// 	"fmt"
// 	"math/bits"
// 	"slices"
// 	"sort"
// )
// 
// // https://space.bilibili.com/206214
// type pair struct{ min, max int }
// 
// func op(a, b pair) pair {
// 	return pair{min(a.min, b.min), max(a.max, b.max)}
// }
// 
// type ST [][16]pair // 16 = bits.Len(5e4)
// 
// func newST(a []int) ST {
// 	n := len(a)
// 	w := bits.Len(uint(n))
// 	st := make(ST, n)
// 	for i, x := range a {
// 		st[i][0] = pair{x, x}
// 	}
// 	for j := 1; j < w; j++ {
// 		for i := range n - 1<<j + 1 {
// 			st[i][j] = op(st[i][j-1], st[i+1<<(j-1)][j-1])
// 		}
// 	}
// 	return st
// }
// 
// // [l,r) 左闭右开
// func (st ST) query(l, r int) int {
// 	k := bits.Len(uint(r-l)) - 1
// 	p := op(st[l][k], st[r-1<<k][k])
// 	return p.max - p.min
// }
// 
// func maxTotalValue(nums []int, k int) (ans int64) {
// 	n := len(nums)
// 	st := newST(nums)
// 	h := hp{{st.query(0, n), 0, n}}
// 
// 	for ; k > 0 && h[0].d > 0; k-- {
// 		fmt.Println(h)
// 		ans += int64(h[0].d)
// 		l, r := h[0].l, h[0].r
// 		h[0].d = st.query(l, r-1)
// 		h[0].r--
// 		heap.Fix(&h, 0)
// 		if r == n && l+1 < n {
// 			heap.Push(&h, tuple{st.query(l+1, n), l + 1, n})
// 		}
// 	}
// 	return
// }
// 
// type tuple struct{ d, l, r int }
// type hp []tuple
// 
// func (h hp) Len() int           { return len(h) }
// func (h hp) Less(i, j int) bool { return h[i].d > h[j].d }
// func (h hp) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
// func (h *hp) Push(v any)        { *h = append(*h, v.(tuple)) }
// func (hp) Pop() (_ any)         { return }
// 
// //
// 
// type data struct{ sumMin, sumMax, lMin, lMax int }
// type todo struct{ todoMin, todoMax int }
// type lazySeg []struct {
// 	l, r int
// 	data
// 	todo
// }
// 
// var todoInit = todo{-1, -1}
// 
// func merge(l, r data) data {
// 	return data{l.sumMin + r.sumMin, l.sumMax + r.sumMax, l.lMin, l.lMax}
// }
// 
// func (t lazySeg) apply(o int, f todo) {
// 	cur := &t[o]
// 	sz := cur.r - cur.l + 1
// 	if f.todoMin >= 0 {
// 		cur.lMin = f.todoMin
// 		cur.sumMin = f.todoMin * sz
// 		cur.todoMin = f.todoMin
// 	}
// 	if f.todoMax >= 0 {
// 		cur.lMax = f.todoMax
// 		cur.sumMax = f.todoMax * sz
// 		cur.todoMax = f.todoMax
// 	}
// 	fmt.Println(o, f, cur)
// }
// 
// func (t lazySeg) maintain(o int) {
// 	t[o].data = merge(t[o<<1].data, t[o<<1|1].data)
// }
// 
// func (t lazySeg) spread(o int) {
// 	f := t[o].todo
// 	if f == todoInit {
// 		return
// 	}
// 	t.apply(o<<1, f)
// 	t.apply(o<<1|1, f)
// 	t[o].todo = todoInit
// }
// 
// func (t lazySeg) build(o, l, r int) {
// 	t[o].l, t[o].r = l, r
// 	t[o].todo = todoInit
// 	if l == r {
// 		return
// 	}
// 	m := (l + r) >> 1
// 	t.build(o<<1, l, m)
// 	t.build(o<<1|1, m+1, r)
// }
// 
// func (t lazySeg) update(o, l, r int, f todo) {
// 	if l <= t[o].l && t[o].r <= r {
// 		t.apply(o, f)
// 		return
// 	}
// 	t.spread(o)
// 	m := (t[o].l + t[o].r) >> 1
// 	if l <= m {
// 		t.update(o<<1, l, r, f)
// 	}
// 	if m < r {
// 		t.update(o<<1|1, l, r, f)
// 	}
// 	t.maintain(o)
// }
// 
// func (t lazySeg) query(o, l, r int) data {
// 	if l <= t[o].l && t[o].r <= r {
// 		return t[o].data
// 	}
// 	t.spread(o)
// 	m := (t[o].l + t[o].r) >> 1
// 	if r <= m {
// 		return t.query(o<<1, l, r)
// 	}
// 	if l > m {
// 		return t.query(o<<1|1, l, r)
// 	}
// 	lRes := t.query(o<<1, l, r)
// 	rRes := t.query(o<<1|1, l, r)
// 	return merge(lRes, rRes)
// }
// 
// // 查询 [l,r] 内最后一个满足 f 的下标
// func (t lazySeg) findLast(o, l, r int, f func(data) bool) int {
// 	if t[o].l > r || t[o].r < l || !f(t[o].data) {
// 		return -1
// 	}
// 	if t[o].l == t[o].r {
// 		return t[o].l
// 	}
// 	t.spread(o)
// 	idx := t.findLast(o<<1|1, l, r, f)
// 	if idx < 0 {
// 		idx = t.findLast(o<<1, l, r, f)
// 	}
// 	return idx
// }
// 
// func maxTotalValue2(nums []int, k int) (ans int64) {
// 	// 二分 + 滑动窗口 + 单调队列
// 	lowD := sort.Search(slices.Max(nums)-slices.Min(nums), func(lowD int) bool {
// 		lowD++
// 		// 1438. 绝对差不超过限制的最长连续子数组(改成求子数组个数)
// 		var minQ, maxQ []int
// 		cnt, left := 0, 0
// 		for right, x := range nums {
// 			for len(minQ) > 0 && x <= nums[minQ[len(minQ)-1]] {
// 				minQ = minQ[:len(minQ)-1]
// 			}
// 			minQ = append(minQ, right)
// 
// 			for len(maxQ) > 0 && x >= nums[maxQ[len(maxQ)-1]] {
// 				maxQ = maxQ[:len(maxQ)-1]
// 			}
// 			maxQ = append(maxQ, right)
// 
// 			for nums[maxQ[0]]-nums[minQ[0]] >= lowD {
// 				left++
// 				if minQ[0] < left {
// 					minQ = minQ[1:]
// 				}
// 				if maxQ[0] < left {
// 					maxQ = maxQ[1:]
// 				}
// 			}
// 
// 			cnt += left
// 			if cnt >= k {
// 				return false
// 			}
// 		}
// 		return true
// 	})
// 
// 	// 单调栈
// 	n := len(nums)
// 	leftLessEq := make([]int, n)
// 	leftGreatEq := make([]int, n)
// 	st1 := []int{-1}
// 	st2 := []int{-1}
// 	for i, x := range nums {
// 		for len(st1) > 1 && nums[st1[len(st1)-1]] > x {
// 			st1 = st1[:len(st1)-1]
// 		}
// 		leftLessEq[i] = st1[len(st1)-1]
// 		st1 = append(st1, i)
// 
// 		for len(st2) > 1 && nums[st2[len(st2)-1]] < x {
// 			st2 = st2[:len(st2)-1]
// 		}
// 		leftGreatEq[i] = st2[len(st2)-1]
// 		st2 = append(st2, i)
// 	}
// 
// 	// Lazy 线段树
// 	t := make(lazySeg, 2<<bits.Len(uint(n-1)))
// 	t.build(1, 0, n-1)
// 	cnt, sum := 0, 0
// 	for i, x := range nums {
// 		t.update(1, leftLessEq[i]+1, i, todo{x, -1})
// 		t.update(1, leftGreatEq[i]+1, i, todo{-1, x})
// 		l := t.findLast(1, 0, i, func(d data) bool { return d.lMax-d.lMin >= lowD })
// 		if l >= 0 {
// 			cnt += l + 1
// 			d := t.query(1, 0, l)
// 			sum += d.sumMax - d.sumMin
// 		}
// 	}
// 
// 	return int64(sum - (cnt-k)*lowD) // 减掉多算的
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.