[LeetCode] Maximum Total from Optimal Activation Order

3645. Maximum Total from Optimal Activation Order

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
long long maxTotal(vector<int>& value, vector<int>& limit) {
long long res = 0;
unordered_map<int,vector<int>> vals;
for(int i = 0; i < value.size(); i++) {
vals[limit[i]].push_back(value[i]);
}
for(auto& [k,v] : vals) {
sort(rbegin(v), rend(v));
for(int i = 0; i < k and i < v.size(); i++) res += v[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/08/17/PS/LeetCode/maximum-total-from-optimal-activation-order/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.