- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 53 lines of C++ from the credited upstream file maximum-total-sum-of-k-selected-elements.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long maxSum(vector<int>& nums, int k, int mul) {8 priority_queue<int, vector<int>, greater<int>> min_heap;9 for (const auto& x : nums) {10 min_heap.emplace(x);11 if (size(min_heap) == k + 1) {12 min_heap.pop();13 }14 }15 int64_t result = 0;16 while (!empty(min_heap)) {17 const auto x = min_heap.top(); min_heap.pop();18 result += x * static_cast<int64_t>(max(mul - static_cast<int>(size(min_heap)), 1));19 }20 return result;21 }22};23 24252627class Solution2 {28public:29 long long maxSum(vector<int>& nums, int k, int mul) {30 partial_sort(begin(nums), begin(nums) + k, end(nums), greater<int>());31 int64_t result = 0;32 for (int i = 0; i < k; ++i) {33 result += nums[i] * static_cast<int64_t>(max(mul - i, 1));34 }35 return result;36 }37};38 39404142class Solution3 {43public:44 long long maxSum(vector<int>& nums, int k, int mul) {45 sort(begin(nums), end(nums), greater<int>());46 int64_t result = 0;47 for (int i = 0; i < k; ++i) {48 result += nums[i] * static_cast<int64_t>(max(mul - i, 1));49 }50 return result;51 }52};53