Show problems as
Classic problem #3434MediumArrayHash TableDynamic ProgrammingGreedyEnumerationPrefix Sum

Maximum Frequency After Subarray Operation

Real-world version: Most Dials Reading k After One Nudge
Tracked in this browser only
Read Maximum Frequency After Subarray Operation on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Dial readings are given as nums.

Choose exactly one contiguous stretch of the readings and add the same whole number to every reading in it. That number may be negative, and it may be zero.

Return the greatest number of readings that can end up equal to k.

Examples

Example 1

Input
nums = [3, 7, 3, 9, 7, 3, 7], k = 7
Output
4

Three readings already show 7. Adding four to the stretch covering positions 0 to 2 turns two threes into sevens while pushing the single 7 inside it off, for a net gain of one, giving four in all.

Example 2

Input
nums = [1, 1, 1, 1, 1], k = 2
Output
5

Adding one to the whole list turns every reading into 2.

Example 3

Input
nums = [7, 7, 7, 7], k = 3
Output
4

Every reading is the same, so one shift moves as many of them onto 3 as the stretch covers, and covering all four is best.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 50
  • 1 <= k <= 50

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_frequency(nums: list[int], k: int) -> int:
Java
public int maxFrequency(int[] nums, int k)