✅C++ | ✅Sorting to get max values | ✅Easy Approach
Approach\nWe just need to find all the adjacent nodes of every node(0 to n-1) and storing them with their values into a data structure(which is vector adj for t
# Approach\nWe just need to find all the adjacent nodes of every node(0 to n-1) and storing them with their values into a data structure(which is vector adj for this code). \n\nThen, For every node (0 to n-1) we store all adjacent nodes\' values in an array and sort it into descreasing order to get max values first then find maximum sum of at most top-k adjacent nodes values and return it.\n\n\n# Complexity\n- Time complexity: \nO(N x E x log(E))\n\n- Space complexity:\nO(N x E) \n\n# Code\n```\nclass Solution \n{\npublic:\n    int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) \n    {\n        int n=vals.size();\n        vector<pair<int, int>> adj[n]; //stores (ai, bi, and bi\'s value) here ai and bi are node connected with an edge\n        \n        for(int i=0; i<edges.size(); i++) //creating undirected graph with node\'s value\n        {\n            adj[edges[i][0]].push_back({edges[i][1], vals[edges[i][1]]});\n            adj[edges[i][1]].push_back({edges[i][0], vals[edges[i][0]]});\n        }\n        \n        int maxi = INT_MIN;\n        vector<int> connectedNodesVals; //stores connected nodes\' value \n        for(int node=0; node<n; node++)\n        {\n            for(auto it:adj[node]) //storing all the adjacent nodes\' value\n            {\n                connectedNodesVals.push_back(it.second);\n            }\n            //sort vals in descreasing order to get top-k max vals\n            sort(connectedNodesVals.begin(), connectedNodesVals.end(), greater<int>()); \n            \n            int i=0, sum=vals[node];\n            maxi = max(maxi, sum); //for handling single node condition & negative nodes\' values \n            while(i<connectedNodesVals.size() && i<k) //calculating max star sum\n            {\n                sum += connectedNodesVals[i++];\n                maxi = max(maxi, sum);\n            }\n            \n            connectedNodesVals.clear(); //clear array for next node\n        }\n        return maxi;\n        \n        \n    }\n};\n```
['Array', 'Graph', 'Sorting', 'C++']