#3645

Maximum Total from Optimal Activation Order

Medium
ArrayTwo PointersGreedySortingHeap (Priority Queue)GreedySorting
LeetCode ↗

Approaches

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

Intuition

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

Group elements by their limits and activate the highest values first. This ensures we maximize the total while respecting the limit constraints.

⚙️

Algorithm

3 steps
  1. 1Step 1: Pair values with their limits and sort by limit.
  2. 2Step 2: Use a max-heap to keep track of the highest values that can be activated.
  3. 3Step 3: Iterate through the sorted pairs, adding values to the heap and activating the top values based on the current active count.
solution.py11 lines
1import heapq
2
3def maxActivationValue(value, limit):
4    items = sorted(zip(value, limit), key=lambda x: x[1])
5    max_total, active_count, max_heap = 0, 0, []
6    for v, l in items:
7        if active_count < l:
8            heapq.heappush(max_heap, -v)
9            active_count += 1
10        max_total += -heapq.heappop(max_heap) if max_heap else 0
11    return max_total

Complexity note: Sorting takes O(n log n) and the heap operations are O(log n) for each element.

  • 1Group elements by limit values.
  • 2Use a max-heap to efficiently manage the highest values.

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