# 2360. Longest Cycle in a Graph ###### tags: `leetcode`,`memo`,`hard` >ref: https://leetcode.com/problems/longest-cycle-in-a-graph/ > ![](https://i.imgur.com/4LjZE2W.png) ![](https://i.imgur.com/veacIM4.png) ![](https://i.imgur.com/6KNcIb6.png) >1. tc O(n) visit at most once >2. sc O(n) record the visit timetag ```java= class Solution { public int longestCycle(int[] edges) { // use visit and increaing time as the length int[] visitT=new int[edges.length]; // int time=1; int ans=-1; int time=1; for(int i=0;i<edges.length;i++){ if(visitT[i]==0){ int next= i; int st=time; while(next!=-1 && visitT[next]==0){ visitT[next]=time++; next=edges[next]; } if( next!=-1 && visitT[next]>=st){ ans=Math.max(ans,time-visitT[next]); // time cur not used, for next loop is ok } } } return ans; } } ```