-
Notifications
You must be signed in to change notification settings - Fork 0
/
1383 - Maximum Performance of a Team.cpp
78 lines (66 loc) · 2.26 KB
/
1383 - Maximum Performance of a Team.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <vector>
#include <algorithm>
#include <numeric>
#include <queue>
#include <list>
class MemoryEfficientSolution
{
public:
int maxPerformance(const int n, std::vector<int> & speed, std::vector<int> & efficiency, const int k) const
{
// sort engineers by their efficiency
std::vector<int> engineers(n);
std::iota(engineers.begin(), engineers.end(), 0);
std::sort(engineers.begin(), engineers.end(), [&] (const int l, const int r) {
return efficiency[l] > efficiency[r];
});
// keep the max sum of all speeds up to engineer i, and their summands
long sum{0}, perf{0};
std::priority_queue<int, std::vector<int>, std::greater<int>> summands;
for (size_t i : engineers)
{
const int e {efficiency[i]}, s {speed[i]};
if (summands.size() == k)
{
const int min = summands.top();
if (min >= s) continue;
sum -= min;
summands.pop();
}
sum += s;
summands.push(s);
perf = std::max(sum * e, perf);
}
return perf % long(1e9 + 7);
}
};
class Solution // faster solution
{
public:
int maxPerformance(const int n, std::vector<int> & speed, std::vector<int> & efficiency, const int k) const
{
// sort engineers by their efficiency
std::vector<std::pair<int, int>> engineers(n);
for (size_t i = 0; i < n; ++i) engineers[i] = std::make_pair(efficiency[i], speed[i]);
std::sort(engineers.begin(), engineers.end(), [] (const auto l, const auto r) {
return l.first > r.first;
});
// keep the max sum of all speeds up to engineer i, and their summands
long sum{0}, perf{0};
std::priority_queue<int, std::vector<int>, std::greater<int>> summands;
for (auto & p : engineers)
{
const int & e {p.first}, & s {p.second};
if (summands.size() == k)
{
const int min = summands.top();
sum -= min;
summands.pop();
}
sum += s;
summands.push(s);
perf = std::max(sum * e, perf);
}
return perf % long(1e9 + 7);
}
};