Created
July 15, 2024 09:18
-
-
Save rishabhgargg/a34f7799d93914d1d654b6717437fcf7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_largest_sum_cycle(n, edges): | |
def dfs(node, visited, stack, path_sum, cycle_sums): | |
visited[node] = True | |
stack[node] = path_sum | |
next_node = edges[node] | |
if next_node != -1: | |
if not visited[next_node]: | |
dfs(next_node, visited, stack, path_sum + next_node, cycle_sums) | |
elif stack[next_node] != -1: | |
# Cycle detected | |
cycle_sum = path_sum - stack[next_node] + next_node | |
cycle_sums.append(cycle_sum) | |
stack[node] = -1 # Remove the node from the current path | |
visited = [False] * n | |
stack = [-1] * n # Keeps track of the nodes in the current path | |
cycle_sums = [] | |
for i in range(n): | |
if not visited[i]: | |
dfs(i, visited, stack, i, cycle_sums) | |
return max(cycle_sums) if cycle_sums else -1 | |
# Example usage | |
n = 23 | |
edges = [4, 4, 14, 13, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21] | |
print(find_largest_sum_cycle(n, edges)) # Output: 45 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment