You are given an integer array nums of length n and an integer k.[1][2]
You may perform the following operation on nums exactly once:
nums[i..j] where 0 <= i <= j <= n - 1.x, and add x to every element in nums[i..j].Your goal is to determine the maximum possible frequency (count) of the value k in the array after performing this single operation. Since you can choose x = 0, you can effectively decide to leave the array unchanged if no modification improves the count of k.[3]
Note: This is a reconstructed statement of an interview problem often titled “Maximum Count of Target After One Operation”, which corresponds to the LeetCode problem known as “Maximum Frequency After Subarray Operation” and has been reported in FAANG (including Amazon) interviews.[2][1]
Input:
nums: an array of integers of length n.k: an integer representing the target value whose frequency you want to maximize.Output:
k in nums after performing the operation once (choosing any subarray and any integer x, possibly x = 0).[1][2]Typical function signature examples:
int maxFrequencyAfterOperation(vector<int>& nums, int k);int maxFrequencyAfterOperation(int[] nums, int k);def maxFrequencyAfterOperation(nums: List[int], k: int) -> int:Input
text nums = [1, 2, 3, 4, 5, 6] k = 1
Output
text 2
Explanation
[1, 2, 3, 4, 5, 6].1 appears once (at index 0).[2][1]nums[2..5] = [3, 4, 5, 6].x = -5 and add it to each element in this subarray:
3 + (-5) = -24 + (-5) = -15 + (-5) = 06 + (-5) = 1[1, 2, -2, -1, 0, 1].1 appears twice (at indices 0 and 5).x can increase the frequency of 1 beyond 2, so the answer is 2.[1][2]Input
text nums = [10, 2, 3, 4, 5, 5, 4, 3, 2, 2] k = 10
Output
text 4
Explanation
10 appears once (at index 0).[2][1]nums[1..9] = [2, 3, 4, 5, 5, 4, 3, 2, 2].x = 8 and add it to each element in this subarray:
2 + 8 = 103 + 8 = 114 + 8 = 125 + 8 = 135 + 8 = 134 + 8 = 123 + 8 = 112 + 8 = 102 + 8 = 10[10, 10, 11, 12, 13, 13, 12, 11, 10, 10].10 appears four times (indices 0, 1, 8, and 9).10 after one operation, so the answer is 4.[1][2]1 <= n == nums.length <= 100000 (i.e., n up to 10^5).[2]1 <= nums[i] <= 50 for all 0 <= i < n.[2]1 <= k <= 50.[2]Performance expectations (to pass typical constraints):
nums (at most 50), which is effectively linear in n.[3]Think of the operation as picking a subarray and “turning” all occurrences of some value t inside that subarray into k, while any existing k in that subarray will be shifted away from k and thus lost. For each possible candidate value t, use a greedy Kadane-style / sliding-window pass over nums to find the subarray where converting t to k yields the maximum net gain (#t gained − #k lost), then add this best gain to the original count of k and take the maximum over all t.[4][3]