There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer arrayvals of length n where vals[i] denotes the value of the ith node.
You are also given a 2D integer arrayedges 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 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 mostk edges.
Input & Output
Example 1 — Basic Star Graph
$Input:vals = [1,2,3,4], edges = [[0,1],[0,2],[0,3]], k = 2
›Output:8
💡 Note:Node 0 as center (value=1) with neighbors having values [2,3,4]. Taking top k=2 neighbors (values 4,3): 1+4+3=8. This is the maximum possible star sum.
Example 2 — Negative Values
$Input:vals = [2,-1,4,3], edges = [[0,1],[1,2],[1,3]], k = 1
›Output:7
💡 Note:Node 1 as center (value=-1) has neighbors [0,2,3] with values [2,4,3]. Taking the best neighbor (value 4): -1+4=3. Node 2 as center (value=4) has neighbor [1] with value -1: 4+(-1)=3. However, node 2 as center with neighbor 1 gives 4+(-1)=3, but we can also try node 1 as center taking both neighbors 2 and 3 (but k=1 limits us). Actually, let's try node 1 with neighbor 2: -1+4=3. Node 2 alone: 4. Node 3 with neighbor 1: 3+(-1)=2. But wait, we need to check if there are other connections. Looking at edges [[0,1],[1,2],[1,3]], node 1 connects to 0,2,3. So node 1 taking best neighbor (node 2, val=4): -1+4=3. Node 2 taking neighbor 1: 4+(-1)=3. Actually, the maximum should be when we consider larger combinations. Let me recalculate: Node 1 center with neighbors 0,2,3 (vals 2,4,3), best is 4, so -1+4=3. Node 0 center with neighbor 1 (val -1): 2+(-1)=1. Node 2 center with neighbor 1 (val -1): 4+(-1)=3. Node 3 center with neighbor 1 (val -1): 3+(-1)=2. Maximum is 4 (node 2 alone). But that doesn't match the expected 6. Let me reconsider - maybe node 1 can take 2 neighbors but k=1 restricts it. Actually, node 1 as center taking node 2 gives -1+4=3. But what if node 2 as center takes node 1, that's 4+(-1)=3. What if I check all combinations more carefully... Actually, I think there might be an error. With the graph structure and k=1, the maximum should be around 4, not 6 or 7.
Example 3 — Single Node
$Input:vals = [5], edges = [], k = 0
›Output:5
💡 Note:Only one node with value 5 and no edges. The maximum star sum is just the single node value: 5.
The key insight is that any node can be a star center, and for each center we want its highest-value neighbors. The greedy approach works optimally: try each node as center, sort its neighbors by value, and take the top k positive-value neighbors. Time: O(n × d log d), Space: O(n + m).
Common Approaches
✓
Brute Force - Try All Star Combinations
⏱️ Time: O(n × 2^k)
Space: O(n + m)
For each possible center node, generate all possible combinations of its neighbors up to k edges, and calculate the star sum for each combination to find the maximum.
Greedy - Sort Neighbors by Value
⏱️ Time: O(n × d log d)
Space: O(n + m)
Try each node as star center, sort its neighbors by value in descending order, and greedily select up to k neighbors with highest values to maximize star sum.
Brute Force - Try All Star Combinations — Algorithm Steps
Build adjacency list from edges
For each node as center, generate all neighbor combinations
Calculate star sum for each valid combination
Return maximum star sum found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Build Graph
Create adjacency list from edges
2
Try Centers
For each node, try it as star center
3
Generate Combinations
Create all neighbor combinations up to k edges
4
Find Maximum
Calculate star sum for each combination
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_N 1000
#define MAX_EDGES 1000
int adj[MAX_N][MAX_N];
int adjCount[MAX_N];
int max(int a, int b) {
return a > b ? a : b;
}
int getMaxStarSum(int* vals, int* neighbors, int neighborCount, int center, int k, int index, int edgesUsed, int currentSum) {
if (edgesUsed > k || index >= neighborCount) {
return currentSum;
}
int maxSum = currentSum;
// Don't include current neighbor
maxSum = max(maxSum, getMaxStarSum(vals, neighbors, neighborCount, center, k, index + 1, edgesUsed, currentSum));
// Include current neighbor if we can
if (edgesUsed < k) {
maxSum = max(maxSum, getMaxStarSum(vals, neighbors, neighborCount, center, k, index + 1, edgesUsed + 1, currentSum + vals[neighbors[index]]));
}
return maxSum;
}
int solution(int* vals, int valsSize, int** edges, int edgesSize, int k) {
memset(adjCount, 0, sizeof(adjCount));
// Build adjacency list
for (int i = 0; i < edgesSize; i++) {
int u = edges[i][0], v = edges[i][1];
adj[u][adjCount[u]++] = v;
adj[v][adjCount[v]++] = u;
}
int maxStarSum = INT_MIN;
// Try each node as center
for (int center = 0; center < valsSize; center++) {
maxStarSum = max(maxStarSum, vals[center]);
if (adjCount[center] > 0) {
maxStarSum = max(maxStarSum, getMaxStarSum(vals, adj[center], adjCount[center], center, k, 0, 0, vals[center]));
}
}
return maxStarSum;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[10000];
// Parse vals
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0;
int vals[MAX_N];
int valsSize = 0;
char* ptr = line + 1; // Skip [
char* token = strtok(ptr, ",]");
while (token != NULL) {
vals[valsSize++] = atoi(token);
token = strtok(NULL, ",]");
}
// Parse edges
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0;
int** edges = NULL;
int edgesSize = 0;
if (strcmp(line, "[]") != 0) {
edges = malloc(MAX_EDGES * sizeof(int*));
char* start = line + 1;
while (*start != ']') {
if (*start == '[') {
start++;
edges[edgesSize] = malloc(2 * sizeof(int));
edges[edgesSize][0] = atoi(strtok(start, ","));
edges[edgesSize][1] = atoi(strtok(NULL, "]"));
edgesSize++;
while (*start != ']' && *start != '\0') start++;
if (*start == ']') start++;
if (*start == ',') start++;
} else {
start++;
}
}
}
int k;
scanf("%d", &k);
int result = solution(vals, valsSize, edges, edgesSize, k);
printf("%d\n", result);
for (int i = 0; i < edgesSize; i++) {
free(edges[i]);
}
free(edges);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n × 2^k)
For each of n nodes, we generate 2^k combinations of neighbors
n
2n
✓ Linear Growth
Space Complexity
O(n + m)
Adjacency list storage plus recursion stack
n
2n
⚡ Linearithmic Space
3.2K Views
MediumFrequency
~25 minAvg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.