LeetCode #3645 — MEDIUM

Maximum Total from Optimal Activation Order

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given two integer arrays value and limit, both of length n.

Initially, all elements are inactive. You may activate them in any order.

  • To activate an inactive element at index i, the number of currently active elements must be strictly less than limit[i].
  • When you activate the element at index i, it adds value[i] to the total activation value (i.e., the sum of value[i] for all elements that have undergone activation operations).
  • After each activation, if the number of currently active elements becomes x, then all elements j with limit[j] <= x become permanently inactive, even if they are already active.

Return the maximum total you can obtain by choosing the activation order optimally.

Example 1:

Input: value = [3,5,8], limit = [2,1,3]

Output: 16

Explanation:

One optimal activation order is:

Step Activated i value[i] Active Before i Active After i Becomes Inactive j Inactive Elements Total
1 1 5 0 1 j = 1 as limit[1] = 1 [1] 5
2 0 3 0 1 - [1] 8
3 2 8 1 2 j = 0 as limit[0] = 2 [0, 1] 16

Thus, the maximum possible total is 16.

Example 2:

Input: value = [4,2,6], limit = [1,1,1]

Output: 6

Explanation:

One optimal activation order is:

Step Activated i value[i] Active Before i Active After i Becomes Inactive j Inactive Elements Total
1 2 6 0 1 j = 0, 1, 2 as limit[j] = 1 [0, 1, 2] 6

Thus, the maximum possible total is 6.

Example 3:

Input: value = [4,1,5,2], limit = [3,3,2,3]

Output: 12

Explanation:

One optimal activation order is:​​​​​​​​​​​​​​

Step Activated i value[i] Active Before i Active After i Becomes Inactive j Inactive Elements Total
1 2 5 0 1 - [ ] 5
2 0 4 1 2 j = 2 as limit[2] = 2 [2] 9
3 1 1 1 2 - [2] 10
4 3 2 2 3 j = 0, 1, 3 as limit[j] = 3 [0, 1, 2, 3] 12

Thus, the maximum possible total is 12.

Constraints:

  • 1 <= n == value.length == limit.length <= 105
  • 1 <= value[i] <= 105​​​​​​​
  • 1 <= limit[i] <= n
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 two integer arrays value and limit, both of length n. Initially, all elements are inactive. You may activate them in any order. To activate an inactive element at index i, the number of currently active elements must be strictly less than limit[i]. When you activate the element at index i, it adds value[i] to the total activation value (i.e., the sum of value[i] for all elements that have undergone activation operations). After each activation, if the number of currently active elements becomes x, then all elements j with limit[j] <= x become permanently inactive, even if they are already active. Return the maximum total you can obtain by choosing the activation order optimally.

Baseline thinking

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

Pattern signal: Array · Two Pointers · Greedy

Example 1

[3,5,8]
[2,1,3]

Example 2

[4,2,6]
[1,1,1]

Example 3

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

Core Insight

What unlocks the optimal approach

  • Group the items by their <code>limit</code> values, as decisions for each <code>limit</code> are independent.
  • For a group with <code>limit = j</code> and <code>m</code> items, its contribution is the sum of the top <code>min(j, m)</code> values.
  • To extract each group's top values, use a min-heap of capacity <code>j</code>: push each <code>value[i]</code>, and whenever the heap size exceeds <code>j</code>, pop the smallest.
  • After processing a group's heap, sum its elements and add to the overall total; repeat for all groups in any order.
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
Upper-end input sizes
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 #3645: Maximum Total from Optimal Activation Order
class Solution {
    public long maxTotal(int[] value, int[] limit) {
        Map<Integer, List<Integer>> g = new HashMap<>();
        for (int i = 0; i < value.length; ++i) {
            g.computeIfAbsent(limit[i], k -> new ArrayList<>()).add(value[i]);
        }
        long ans = 0;
        for (var e : g.entrySet()) {
            int lim = e.getKey();
            var vs = e.getValue();
            vs.sort((a, b) -> b - a);
            for (int i = 0; i < Math.min(lim, vs.size()); ++i) {
                ans += vs.get(i);
            }
        }
        return ans;
    }
}
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)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
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.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.

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.