Advertisement
jorupp

https://leetcode.com/problems/maximum-star-sum-of-a-graph

Jul 12th, 2023
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. function maxStarSum(vals: number[], edges: number[][], k: number): number {
  2. const links = new Map<number, number[]>();
  3. function add(i1: number, i2: number) {
  4. if (links.has(i1)) {
  5. links.get(i1).push(vals[i2]);
  6. }
  7. else {
  8. links.set(i1, [vals[i2]]);
  9. }
  10. }
  11. for(const edge of edges) {
  12. const [i1, i2] = edge;
  13. add(i1, i2);
  14. add(i2, i1);
  15. }
  16.  
  17. let max = -10000 * (k+2);
  18. for(let i=0; i<vals.length; i++) {
  19. const thisLinks = links.get(i) ?? [];
  20. // take the best K links, but don't take any negative numbers
  21. const sum = thisLinks.sort((a,b) => b-a).slice(0,k).filter(i => i>0)
  22. // add the center node (it's not optional)
  23. .concat([vals[i]])
  24. // sum
  25. .reduce((a,b) => a + b, 0);
  26. if (sum > max) max = sum;
  27. }
  28. return max;
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement