Check If Array Can Converge To Same Value - FollowUp
Given an integer x and a list of integers nums, determine whether it is possible to make every element of nums equal to the same integer value y.
For each element, you may independently add or subtract any integer amount from 0 to x, inclusive. The chosen final value y must be the same for all elements.
Class
ArrayEquivalenceChecker
Method
Can Make Full Array Equivalent
boolean canMakeEquivalent(List<Integer> nums, int x)
- Returns
true if there exists an integer y such that every element can be changed to y.
- For every element
num, the final value y must satisfy num - x ≤ y ≤ num + x.
- Returns
false if no such common value y exists.
Deterministic Rule
The method only returns whether such a value y exists. It does not need to return y. Therefore, the output is always deterministic.
Constraints
1 ≤ nums.size() ≤ 100,000
-1,000,000 ≤ nums[i] ≤ 1,000,000
1 ≤ x ≤ 1,000,000
- All values in
nums are integers.
Examples
Example 1
canMakeEquivalent(nums = [4, 5, 6], x = 1)
Output: true
Explanation: All elements can be changed to 5. The element 4 can increase by 1, 5 can remain unchanged, and 6 can decrease by 1.
Example 2
canMakeEquivalent(nums = [2, 6], x = 1)
Output: false
Explanation: The first element can become only a value from 1 to 3, while the second element can become only a value from 5 to 7. There is no common value.
Example 3
canMakeEquivalent(nums = [10, 14, 12], x = 2)
Output: true
Explanation: All elements can be changed to 12. Each element is within distance 2 from 12.
Example 4
canMakeEquivalent(nums = [1, 8, 4], x = 2)
Output: false
Explanation: No single integer value can be reached from all elements using at most 2 change per element.