-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-star-sum-of-a-graph.cpp
32 lines (31 loc) · 1.2 KB
/
maximum-star-sum-of-a-graph.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
// Time: O(n)
// Space: O(n)
// quick select
class Solution {
public:
int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) {
vector<vector<int>> adj(size(vals));
for (const auto& e : edges) {
if (vals[e[1]] > 0) {
adj[e[0]].emplace_back(e[1]);
}
if (vals[e[0]] > 0) {
adj[e[1]].emplace_back(e[0]);
}
}
int result = numeric_limits<int>::min();
for (int u = 0; u < size(vals); ++u) {
if (1 <= k && k <= size(adj[u])) {
nth_element(begin(adj[u]), begin(adj[u]) + k - 1, end(adj[u]),
[&](const auto& a, const auto& b) {
return vals[a] > vals[b];
});
}
result = max(result, vals[u] + accumulate(cbegin(adj[u]), cbegin(adj[u]) + min(k, static_cast<int>(size(adj[u]))), 0,
[&](const auto& total, const auto& x) {
return total + vals[x];
}));
}
return result;
}
};