Description

You are given an integer array nums of length n where nums is a permutation of [0, n-1]. Build a set starting with A[i], then A[A[i]], then A[A[A[i]]], etc. Return the longest length of a set.

Examples

Input:nums = [5,4,0,3,1,6,2]
Output:4
Explanation:

Set {5,6,2,0} has length 4.

Input:nums = [1,0,2,4,3]
Output:3
Explanation:

Starting from index 0: 0 → nums[0]=1 → nums[1]=0 (cycle back, length 2). Starting from index 2: 2 → nums[2]=2 (self-loop, length 1). Starting from index 3: 3 → nums[3]=4 → nums[4]=3 (cycle back, length 2). Starting from index 4: 4 → nums[4]=3 → nums[3]=4 (cycle back, length 2). The longest cycle has length 2.

Input:nums = [2,1,3,0]
Output:2
Explanation:

Starting from index 0: 0 → nums[0]=2 → nums[2]=3 → nums[3]=0 (cycle back, length 3). Starting from index 1: 1 → nums[1]=1 (self-loop, length 1). All indices are covered by these cycles, so the longest length is 3.

Constraints

  • 1 ≤ nums.length ≤ 10^5
  • 0 ≤ nums[i] < nums.length

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!