Timeline
timeline
2025-10-21
init
enumeration
Problem:
WA
First look at the WA code:
1 |
|
For input
1 | nums = [5,64] |
The above code is WA because it only enumerates the mode with the highest final frequency, which we call the target mode, only within the values in nums. In fact, each number can undergo one operation, and if two numbers become equal after one operation, that is also valid.
AC
The reason for the WA above is mainly that we did not enumerate completely. For a value nums[i], we need to find values in nums that lie in [nums[i]-k, nums[i]+k]; such values can become the target mode through one operation. However, considering only nums[i] is incorrect because nums[i] can also become any value in [nums[i]-k, nums[i]+k] as the target mode through one operation.
Then do we need to enumerate all values that nums[i] can become as the target mode through one operation? The answer is no.
Core Concept
- Sorted Array
nums - Operable interval of each element:
[nums[i]-k, nums[i]+k] - Enumerate target mode val → count the number of elements that can become val
Define window[val-k, val+k]:
- Left boundary l: the leftmost element contained in the window
- Right boundary r: the rightmost element contained in the window
range_size = r - l + 1
Maximum frequency:
Key observation
Only when the left or right boundary l or r of the window changes,
range_sizewill change → f_i may increase
- Assume val ∈
[nums[r]-k, nums[r+1]-k):- r unchanged
- l unchanged
- range_size constant → f_i unchanged
- All val inside the intervalWill not increase the maximum frequency→ No need to enumerate
Critical point analysis
Critical points of window boundary changes:
- Left boundary l change: val - k = nums[i] (left element just enters/leaves the window)
- Right boundary r change: val + k = nums[i] (right element just enters/leaves the window)
That is,Only when val equals some nums[i] ± k or nums[i] itself, the window boundary will change.
- val = nums[i] → corresponds to the window covering nums[i] itself
- val = nums[i] - k → the left boundary of the window just covers nums[i]
- val = nums[i] + k → the right boundary of the window just covers nums[i]
These three values areall possible critical points that can change the window range
In summary: we only need to enumerate the boundary values, i.e., enumerate {nums[i]-k, nums[i], nums[i]+k}.
1 |
|
