Problem Β· Graph

Converging Maze: Largest Sum Cycle

Learn this problem
● MediumJuspayNEW GRADOA

Problem statement

You are given a maze with N cells. Each cell may have multiple entry points but not more than one exit (i.e. entry/exit points are unidirectional doors like valves).

The cells are named with an integer value from 0 to N-1.

You have to find: The sum of the largest sum cycle in the maze. Return -1 if there are no cycles.

Sum of a cycle is the sum of the node number of all nodes in that cycle.

Function

largestSumCycle(edge: int[]) β†’ long

Complete largestSumCycle with the following parameter:

  • int[] edge: an array of length N, where edge[i] is the cell reached from cell i in one step, or -1 when cell i has no exit. The value of N is edge.length.

Returns

long: the largest sum of cell numbers in any cycle, or -1 if the maze has no cycle

πŸ€— A very special thanks to a fantastic friend for all the help!

Examples

Example 1

edge = [4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21]return = 45
The cycle 9 β†’ 8 β†’ 0 β†’ 4 β†’ 13 β†’ 11 β†’ 9 has node sum 9 + 8 + 0 + 4 + 13 + 11 = 45, the largest cycle sum.

Constraints

  • 1 ≤ edge.length ≤ 105
  • -1 ≤ edge[i] < edge.length

More Juspay problems

drafts saved locally
public long largestSumCycle(int[] edge) {
  // write your code here
}
edge[4, 4, 1, 4, 13, 8, 8, 8, 0, 8, 14, 9, 15, 11, -1, 10, 15, 22, 22, 22, 22, 22, 21]
expected45
checking account