#3691

Maximum Total Subarray Value II

Hard
ArrayGreedySegment TreeHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n² log n)Space O(n)

Use a sliding window approach with precomputed max/min values to efficiently calculate the value of subarrays, allowing us to quickly find the top k values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute max and min values for all subarrays using a sparse table.
  2. 2Step 2: For each starting index, calculate the values of subarrays and store them in a max-heap.
  3. 3Step 3: Extract the top k values from the heap and sum them for the result.
solution.py13 lines
1import heapq
2
3def maxTotalValue(nums, k):
4    n = len(nums)
5    max_heap = []
6    for l in range(n):
7        current_max = nums[l]
8        current_min = nums[l]
9        for r in range(l, n):
10            current_max = max(current_max, nums[r])
11            current_min = min(current_min, nums[r])
12            heapq.heappush(max_heap, current_max - current_min)
13    return sum(heapq.nlargest(k, max_heap))

Complexity note: The complexity arises from calculating values for all subarrays and maintaining a heap for the top k values.

  • 1Subarray values depend on the difference between max and min.
  • 2Selecting overlapping subarrays can maximize total value.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.