Loading...
You are given an integer array nums and a non-negative integer k.
Consider an operation where you pick an index i that has not been picked before, and replace nums[i] with any integer in the range [nums[i] - k, nums[i] + k]. You may perform this operation any number of times, but each index can be picked at most once.
Return the maximum number of elements that can all hold the same value.
Because each index is chosen at most once and the choices are independent, an element with original value v can be turned into a target t exactly when t lies in [v - k, v + k]. The answer is therefore the largest set of elements that share at least one common reachable value.
Input: nums = [4,6,1,2], k = 2
Output: 3
Explanation: Turn the 6 into 4 (from range [4,8]) and the 2 into 4 (from range [0,4]),
giving [4,4,1,4]. Three elements now equal 4, and no common value is reachable by four
elements, so the answer is 3.
Input: nums = [1,1,1,1], k = 10
Output: 4
Explanation: Every element already equals 1, so all four share a common value without
any operation.
nums.length ≤105nums[i] ≤105Click "Run" to test with sample cases or "Submit" to run all tests.