AmazonOA #33
Find Min Sync Time (Circular Servers)
Estimated MediumJudge-ready
Topics (AI-labelled)In-place ArraysGreedy
Servers numbered 1..total form a ring, and moving between adjacent servers takes 1. You may start at any server in the list to visit. Find the shortest time to visit all the specified servers.
Input
The first line contains total n (1≤n≤total≤100000); the second line contains the n server numbers to visit (1..total). A repeated number only needs to be visited once.
Output
Output a single integer, the answer.
Example 1
Input:
8 3
2 4 7
Output:
5
Example 2
Input:
5 1
3
Output:
0
Example 3
Input:
4 4
1 2 3 4
Output:
3
Example notes
Example 1: the largest gap has length 3, and the ring length 8 minus 3 gives 5; for example, going from 4 toward 2 and then around to 7 takes 5 steps in total. Example 2: there is only one target, so you start there and the time is 0. Example 3: walking 3 consecutive steps along the ring visits all four points.
Editorial
Loading solution…