← 返回 amazon 的题目列表Minimum Replacements to Make Every Value Contiguous
类型:online_judge
Problem Description
You are given an integer array arr of length n. In one operation, you may choose two integers x and y, and replace all occurrences of x in the array with y simultaneously.
Your goal is to use the minimum number of operations so that in the final array, every distinct value appears in one contiguous segment only.
In other words, if a value v appears at positions l and r in the final array, then every position between l and r must also contain v.
Adjacent duplicate values do not affect the answer. For example, [1,1,2,1] can be compressed to [1,2,1].
Return the minimum number of operations required.
Input Format
n
arr[0] arr[1] ... arr[n-1]
Output Format
minimum number of operations
Constraints
1 <= n <= 2 * 10^5
-10^9 <= arr[i] <= 10^9
Example 1
Input:
4
1 2 1 3
Output:
1
Explanation: Replace all 2s with 1, obtaining [1,1,1,3].
Example 2
Input:
5
1 2 1 3 2
Output:
2
Explanation: The occurrence ranges of the values overlap, so they must eventually be merged into one block, requiring 2 operations.
Example
Input
4
1 2 1 3
Output
1