Maximum Frequency After Subarray Operation - Problem

You are given an array nums of length n. You are also given an integer k.

You perform the following operation on nums once:

  • Select a subarray nums[i..j] where 0 <= i <= j <= n - 1
  • Select an integer x and add x to all the elements in nums[i..j]

Find the maximum frequency of the value k after the operation.

Input & Output

Example 1 — Basic Transformation
$ Input: nums = [1,2,4,2], k = 4
Output: 3
💡 Note: Select subarray [1,3] and add x=2. Array becomes [1,4,4,4]. The frequency of 4 is 3.
Example 2 — No Transformation Needed
$ Input: nums = [1,4,4,2,4], k = 4
Output: 4
💡 Note: Select subarray [3,3] and add x=2. Array becomes [1,4,4,4,4]. The frequency of 4 is 4.
Example 3 — Single Element
$ Input: nums = [5], k = 3
Output: 1
💡 Note: Select subarray [0,0] and add x=-2. Array becomes [3]. The frequency of 3 is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i], k ≤ 109

Visualization

Tap to expand
Maximum Frequency After Subarray OperationOriginal Array1242index 0index 1index 2index 3Target: k = 4Initial count: 1Transform subarray [1,3] by adding x = 21464unchanged2+2=44+2=62+2=4Better choice: frequency of k=4 becomes 3Count of 4: 2(but 6 ≠ 4)
Understanding the Visualization
1
Input
Array [1,2,4,2] with target k=4
2
Transform
Add x=2 to subarray [1,3]: elements 2→4, 4→6, 2→4
3
Result
Array becomes [1,4,6,4], but better choice gives [1,4,4,4]
Key Takeaway
🎯 Key Insight: Try all meaningful transformations on all subarrays to maximize target frequency
Asked in
Google 12 Microsoft 8 Amazon 15
8.5K Views
Medium Frequency
~35 min Avg. Time
180 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen