#P12123. Maximize Distinct Portals Visited

    ID: 14221 Type: Default 1000ms 256MiB

Maximize Distinct Portals Visited

Maximize Distinct Portals Visited

In an ancient ruin, there are \(n\) teleportation portals arranged in a row. Stepping into the \(i\)-th portal teleports you to immediately before the portal numbered \(a_i\). You may exit at any time or continue by stepping into the portal you are currently in.

You need to choose one portal to enter and then continuously follow the teleportation chain. In addition, you are allowed to use a single magic jump: from some portal \(j\), you can move to one of its adjacent portals (either \(j-1\) or \(j+1\)). Determine the maximum number of different portals that can be reached. Note that even if a portal is visited multiple times, it is counted only once.

inputFormat

The first line contains an integer \(n\) (\(1 \le n \le 10^5\)), the number of portals. The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (each in the range \([1,n]\)), where entering portal \(i\) teleports you to a position before portal \(a_i\).

outputFormat

Output a single integer: the maximum number of distinct portals that can be reached.

sample

3
2 3 1
3

</p>