My first instinct was greedy and it was wrong.
Reframe the problem by considering the difference array d[i] = k - a[i]. We need to find a contiguous subarray where all d[i] are equal (to some value x) and maximize the count of zeros in d after adding x to that subarray. Use a hash map to track the maximum frequency of each difference value within a sliding window, ensuring all elements in the window share the same d[i].
Pro tip: Clarify that x can be any integer, including negative, and that the operation is applied at most once. This shows attention to edge cases and prevents misinterpretation.
Compute the difference array d[i] = k - a[i]. The goal becomes: choose a contiguous subarray and add a constant x to all d[i] in it, such that the number of zeros in d is maximized.
After adding x to a subarray, an element becomes zero if d[i] + x = 0, i.e., x = -d[i]. Thus, all elements in the chosen subarray must have the same d[i] value to become zero simultaneously.
Scan the array and use a hash map to track the maximum frequency of each d[i] value within a sliding window where all elements have the same d[i]. The window length is the count of elements that can be made zero.
Elements with d[i] = 0 are already zero and can be included in the count without needing the operation. They can be part of the subarray if x = 0, or counted separately if the subarray does not include them.
The answer is the maximum over all possible x of (number of zeros in d after operation). This is equivalent to the maximum frequency of any d[i] value in a contiguous subarray, plus any zeros outside that subarray if x ≠ 0.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.