1. Problem Understanding

The problem gives us an array called edge[], where every index represents a node (cell) in a directed graph.

Each node can have at most one outgoing edge.

Our task is to:

  • Identify all cycles in the graph.
  • Calculate the sum of node indices belonging to each cycle.
  • Return the maximum cycle sum.
  • If there is no cycle, return -1.

Example:

Code
Input:  edge = [1, 2, 0, -1]
Output: 3

Let's understand the array:

NodeOutgoing edge
01
12
20
3-1

This represents:

Code
0 → 1 → 2 → 0

We return to node 0, so a cycle exists.

Cycle sum:

Code
0 + 1 + 2 = 3

Node 3 has no outgoing edge because its value is -1.

2. Understanding the Graph Concept

Before implementing the solution, let's understand what a directed graph is.

A graph contains:

  • Vertices (Nodes): The individual cells.
  • Edges: Connections between nodes.
  • Directed edges: Connections that have a specific direction.

For example:

Directed graph

0

1

2

2 → 0 closes the cycle

The directed path returns to its starting node.

A cycle occurs when we follow the outgoing edges and eventually reach a node that is already part of the current path.

For this problem, we don't need a general graph adjacency list because each node has only one outgoing edge. The given array itself represents the graph.

3. What Algorithm Should We Use?

We can solve this problem using Graph Traversal with Visited Tracking and Path Indexing.

We maintain three important things:

  1. A visited array.
  2. A path index array.
  3. A variable to store the maximum cycle sum.

Let's understand why each one is required.

A. Visited Array

C#
bool[] visited = new bool[n];

This array tells us whether a node has already been visited.

For example:

Code
visited = [true, true, true, false]

This means:

  • Node 0 is visited.
  • Node 1 is visited.
  • Node 2 is visited.
  • Node 3 is not visited.

Why do we need it?

Without visited, we might process the same nodes repeatedly, resulting in unnecessary work.

B. Path Index Array

C#
int[] pathIndex = new int[n];

Array.Fill(pathIndex, -1);

This is the most important part of our cycle detection logic.

pathIndex[] stores the position of each node in the current traversal path.

Consider:

Code
path = [0, 1, 2]

The corresponding path indices are:

NodePath index
00
11
22

Suppose we reach node 1 again.

Since:

Code
pathIndex[1] = 1

We know that the cycle starts at position 1.

Therefore, the cycle is:

Code
1 → 2 → 0 → 1

For our example, if the path were [0, 1, 2] and the next node were 0, the cycle would start at position 0.

C. Maximum Sum

C#
int maxSum = -1;

This stores the highest cycle sum found so far.

We initialize it to -1 because the problem requires returning -1 when no cycle exists.

4. Cycle Detection – Understanding the Main Logic

This is the most important code:

C#
while (current != -1 && !visited[current])

The loop runs while:

  • The current node is not -1.
  • The current node has not already been visited.

Inside the loop:

C#
visited[current] = true;

pathIndex[current] = path.Count;

path.Add(current);

current = edge[current];

Let's understand each statement.

Step 1:

C#
visited[current] = true;

Mark the current node as visited.

Step 2:

C#
pathIndex[current] = path.Count;

Store the current node's position in the traversal path.

Step 3:

C#
path.Add(current);

Add the current node to our path.

Step 4:

C#
current = edge[current];

Move to the next node using the outgoing edge.

This continues until we reach -1 or a previously visited node.

5. Complete C# Code

Here is the complete implementation using the same method signature provided in the question.

C#
class Solution {
    public int largestSumCycle(int[] edge) {

        int n = edge.Length;

        // Track visited nodes
        bool[] visited = new bool[n];

        // Store the position of each node in the current path
        int[] pathIndex = new int[n];

        Array.Fill(pathIndex, -1);

        int maxSum = -1;

        // Start traversal from every unvisited node
        for (int i = 0; i < n; i++) {

            if (visited[i])
                continue;

            List<int> path = new List<int>();

            int current = i;

            // Traverse until no edge or an already visited node
            while (current != -1 && !visited[current]) {

                visited[current] = true;

                pathIndex[current] = path.Count;

                path.Add(current);

                current = edge[current];
            }

            // Check whether the current node belongs
            // to the current traversal path
            if (current != -1 && pathIndex[current] != -1) {

                int sum = 0;

                // Calculate only the cycle nodes
                for (int j = pathIndex[current]; j < path.Count; j++) {

                    sum += path[j];
                }

                maxSum = Math.Max(maxSum, sum);
            }

            // Reset path index for the next traversal
            foreach (int node in path) {

                pathIndex[node] = -1;
            }
        }

        return maxSum;
    }
}

Note about integer range: The theoretical maximum cycle sum under the given constraints can exceed Int32.MaxValue. For complete numerical correctness in C#, use long for the sum and change the return type to long if the coding platform permits it. The code above follows your requested int signature.

6. Understanding the Complete Code – Line by Line

Step 1: Get the array size

C#
int n = edge.Length;

This returns the total number of nodes.

For example:

Code
edge = [1, 2, 0, -1]

n = 4

The nodes are 0, 1, 2, 3.

Step 2: Create the visited array

C#
bool[] visited = new bool[n];

Initially:

Code
visited = [false, false, false, false]

Whenever we visit a node, we mark it as true.

Step 3: Create the path index array

C#
int[] pathIndex = new int[n];

Array.Fill(pathIndex, -1);

Initially:

Code
pathIndex = [-1, -1, -1, -1]

Here, -1 means the node is not currently present in the traversal path.

Step 4: Start the traversal

C#
for (int i = 0; i < n; i++) {

    if (visited[i])
        continue;

We check every node.

If a node is already visited, we skip it.

Why?

Because its outgoing path has already been explored.

Step 5: Create a new traversal path

C#
List<int> path = new List<int>();

int current = i;

The list stores the nodes visited during the current traversal.

For example:

Code
path = [0, 1, 2]

Step 6: Traverse the graph

C#
while (current != -1 && !visited[current])

This checks whether traversal can continue.

If the current node is -1, there is no outgoing edge.

If the current node is already visited, we stop and check whether a cycle exists.

Step 7: Detect the cycle

C#
if (current != -1 && pathIndex[current] != -1)

This condition is extremely important.

It checks two things:

  1. We did not reach -1.
  2. The current node belongs to the current traversal path.

If both conditions are true, we found a cycle.

Step 8: Calculate the cycle sum

C#
for (int j = pathIndex[current]; j < path.Count; j++) {

    sum += path[j];
}

We start from the position where the cycle begins and add all remaining nodes in the path.

We do not include nodes that appear before the cycle.

Step 9: Update maximum sum

C#
maxSum = Math.Max(maxSum, sum);

Compare the newly calculated cycle sum with the previous maximum.

Step 10: Reset the path index

C#
foreach (int node in path) {
    pathIndex[node] = -1;
}

This prepares the path index array for the next traversal.

We reset pathIndex, but we do not reset visited.

7. Dry Run – Example 1

Input:

Code
edge = [1, 2, 0, -1]

Initially:

Code
visited   = [false, false, false, false]
pathIndex = [-1, -1, -1, -1]
maxSum    = -1

Iteration 1: Starting from node 0

Current node = 0

StepCurrentPathNext
10[0]1
21[0, 1]2
32[0, 1, 2]0

Now we reach node 0 again.

Our path index array is:

Code
pathIndex = [0, 1, 2, -1]

Since pathIndex[0] = 0, a cycle exists.

Cycle:

Code
0 → 1 → 2 → 0

Calculate:

Code
sum = 0 + 1 + 2
sum = 3

Update:

Code
maxSum = 3

Iteration 2: Starting from node 1

Node 1 is already visited, so skip it.

Iteration 3: Starting from node 2

Node 2 is already visited, so skip it.

Iteration 4: Starting from node 3

Node 3 points to -1.

No cycle exists.

Final result:

Output: 3

8. Dry Run – Example 2

Input:

Code
edge = [2, 0, -1, 2]

Graph:

Connections

1

0

2

-1

3

2

Traversal from node 0:

Code
0 → 2 → -1

No cycle.

Traversal from node 1:

Code
1 → 0

Node 0 was already visited in a previous traversal.

But:

Code
pathIndex[0] = -1

Therefore, node 0 does not belong to the current path, and no cycle is detected.

Traversal from node 3:

Code
3 → 2

Node 2 was visited previously, but it is not part of the current path.

Again, no cycle.

Final result:

Output: -1

9. Why Do We Need Both visited[] and pathIndex[]?

This is the most important interview concept in this problem.

visited[]pathIndex[]
Tracks whether a node was visited before.Tracks whether a node belongs to the current path.
Prevents repeated traversal.Helps identify a cycle.
Remains true after traversal.Reset after each traversal.

Consider:

Code
Traversal 1: 0 → 1 → 2 → -1

Traversal 2: 3 → 2

Node 2 was visited in the first traversal.

When traversal 2 reaches node 2:

Code
visited[2] = true
pathIndex[2] = -1

This is not a cycle because node 2 does not belong to the current traversal path.

Remember: Visiting an already visited node does not always mean a cycle exists. It must belong to the current path.

10. Complexity Analysis

ComplexityValueExplanation
Time ComplexityO(n)Every node is visited at most once.
Auxiliary SpaceO(n)Visited array, path index array and traversal list.

Why is the time complexity O(n)?

Suppose there are 100,000 nodes.

  • Every node is processed at most once.
  • Every node is added to a path at most once.
  • Every path is reset only for its own nodes.
  • We don't repeat graph traversal.

Therefore, total time complexity is O(n).

Final Summary

Largest Sum Cycle – Key Points

  • Algorithm: Graph traversal with cycle detection.
  • visited[]: Tracks previously visited nodes.
  • pathIndex[]: Identifies nodes in the current path.
  • path: Stores the current traversal.
  • maxSum: Stores the maximum cycle sum.
  • Time: O(n).
  • Space: O(n).