[LeetCode] Maximum Star Sum of a Graph

2497. Maximum Star Sum of a Graph

There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node.

You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

A star graph is a subgraph of the given graph having a center node containing 0 or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.

The image below shows star graphs with 3 and 4 neighbors respectively, centered at the blue node.

The star sum is the sum of the values of all the nodes present in the star graph.

Given an integer k, return the maximum star sum of a star graph containing at most k edges.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) {
int n = vals.size();
vector<vector<int>> cost(n);
for(auto e : edges) {
int u = e[0], v = e[1];
int uu = vals[u], vv = vals[v];
if(vv > 0) cost[u].push_back(vv);
if(uu > 0) cost[v].push_back(uu);
}
int res = INT_MIN;
for(int i = 0; i < n; i++) {
sort(rbegin(cost[i]), rend(cost[i]));
int now = 0;
for(int j = 0; j < k and j < cost[i].size(); j++) {
now += cost[i][j];
}
res = max(res, now + vals[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/maximum-star-sum-of-a-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.