Skip to main content

Maximum Total Subarray Value II - Solution & Explanation

HardArrayGreedySegment TreeHeap (Priority Queue)15 min readAsked at: Amazon, Microsoft, Google
Practice this 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)

Approach Overview

Problem Overview: You are given an integer array and must compute the maximum possible total value obtained from subarrays according to the scoring rule defined in the problem. The challenge is efficiently identifying the best subarrays while avoiding overlapping or redundant calculations as the array size grows.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

Enumerate every possible subarray using two nested loops for the start and end index. For each candidate range, compute its value by scanning the subarray and applying the scoring rule. This approach is useful for verifying correctness on small inputs but becomes impractical quickly because the number of subarrays is O(n²) and computing the value for each can take another O(n). Arrays larger than a few hundred elements will already be too slow.

Approach 2: Prefix Processing with Priority Queue (O(n^2 log n) time, O(n) space)

Precompute helper information such as prefix sums or other range statistics depending on the scoring formula. Instead of recalculating values repeatedly, maintain candidate subarrays and push them into a priority queue ordered by their potential contribution. Each step extracts the best candidate and expands or splits the range to generate new candidates. This reduces redundant computation but still explores many overlapping intervals. The heap improves selection of the next best subarray but the number of generated candidates can still reach O(n²).

Approach 3: Greedy Expansion with Segment Tree + Heap (O(n log n) time, O(n) space)

The optimal strategy treats each index or prefix boundary as a potential start of a high-value subarray. A segment tree stores range statistics (such as maximum prefix contribution or best extension point) so you can query the optimal end index for a given start in O(log n). Each candidate subarray is pushed into a heap (priority queue) ordered by its total value. When the best interval is chosen, the remaining search space is split into smaller intervals and reinserted as new candidates. This greedy best-first search avoids scanning the array repeatedly and guarantees that the highest-value segments are discovered first.

The key insight: instead of evaluating every subarray, treat the search space as ranges and always expand the currently best candidate. Efficient range queries from the array via the segment tree keep candidate generation fast while the heap ensures correct ordering.

Recommended for interviews: Start by explaining the brute force idea to show you understand the subarray search space. Then transition to the optimized greedy strategy using a heap and segment tree. Interviewers expect the O(n log n) solution because it demonstrates knowledge of advanced data structures and how to combine range queries with priority-based exploration.

Solution

Consider enumerating the left boundary l of the subarray. As the right boundary r moves to the right, the value of the subarray nums[l..r] increases monotonically. This is because the maximum value within the interval can only increase (or remain unchanged), while the minimum value can only decrease (or remain unchanged). Thus, their difference, max(nums[l..r]) - min(nums[l..r]), possesses a monotonically non-decreasing property.

This implies that for each fixed left endpoint l, we have a monotonically increasing sequence of length n - l, where the i-th element represents the value of nums[l..l+i]. The problem then transforms into: Given n monotonically increasing sequences, find the sum of the top k largest elements across all sequences.

Since the last element of each sequence (i.e., when r = n - 1) is the maximum value of that sequence, we can utilize a max-heap (priority queue) to filter them efficiently:

  1. Initialization: Push the last element of each sequence (where r = n - 1) along with its coordinates, represented as (val, l, n - 1), into the max-heap.
  2. Iterative Greedy Choice: Repeat the operation k times. In each iteration, pop the top element (val, l, r) from the heap and accumulate val into the total answer. If r > l, it indicates that there are still smaller, next-largest values remaining in this sequence. We then compute the value of the previous element in the same sequence, (l, r - 1), and push it back into the heap.
  3. Range Minimum/Maximum Query Optimization: To query both the maximum and minimum values of any subarray [l, r] in \mathcal{O}(1) time, we can precompute a Sparse Table (ST).

The time complexity is \mathcal{O}(n log n + k log n), and the space Complexity is \mathcal{O}(n log n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subarray EnumerationO(n^3)O(1)Understanding the scoring rule or validating logic on very small arrays
Prefix Processing + Heap CandidatesO(n^2 log n)O(n)When partial range reuse helps but full optimization is not required
Greedy with Segment Tree + Priority QueueO(n log n)O(n)General optimal solution for large arrays and interview settings

Video Solution

Maximum Total Subarray Value II | Leetcode 3691 | Top K from Sorted Structures Pattern | Concepts 4 • codestorywithMIK • 13,203 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Maximum Total Subarray Value II easy or hard?
Maximum Total Subarray Value II is considered a Hard problem with a low acceptance rate around 22%. The difficulty comes from combining greedy reasoning with advanced data structures like heaps and segment trees to achieve an O(n log n) solution.
Maximum Total Subarray Value II Python/Java solution
Python, Java, C++, and Go implementations typically follow the same pattern: build a segment tree for range queries, maintain a max heap of candidate intervals, and iteratively extract and split the best interval until all contributions are processed.
How to solve Maximum Total Subarray Value II in O(n log n)?
Preprocess the array to enable fast range evaluation, typically with prefix data and a segment tree. For each candidate start or interval, query the segment tree to find the best possible extension. Push candidates into a max heap ordered by subarray value and repeatedly expand the best interval while splitting remaining ranges.
What is the best approach for Maximum Total Subarray Value II?
The most efficient approach uses a greedy best-first search with a priority queue and a segment tree for fast range queries. Each candidate subarray is evaluated based on its potential value and stored in a heap. The segment tree helps find the optimal extension or boundary for a range in O(log n), resulting in an overall complexity of O(n log n).
Is Maximum Total Subarray Value II asked at Google/Amazon/Meta?
Hard array and range-query problems that combine greedy logic with segment trees or priority queues frequently appear in interviews at companies like Google, Amazon, and Meta. This problem tests the ability to combine multiple data structures for efficient range optimization.
What data structure is used in Maximum Total Subarray Value II?
The optimal solution relies on a segment tree for fast range queries and a priority queue (heap) for selecting the next highest-value candidate subarray. These structures work together to efficiently explore the best intervals in the array.
What is the time complexity of Maximum Total Subarray Value II?
The optimal solution runs in O(n log n) time and uses O(n) space. The log n factor comes from segment tree range queries and heap push/pop operations while processing candidate subarrays.

Ready to solve this problem?

Practice Maximum Total Subarray Value II with our built-in code editor and test cases.

Practice on FleetCode