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: 2
💡 Note: Select subarray [1,1] and add x=2. Array becomes [1,4,4,2]. The frequency of 4 is 2.
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 Operation INPUT Array: nums 1 i=0 2 i=1 4 i=2 2 i=3 Input Values nums = [1, 2, 4, 2] k = 4 n = 4 Goal Maximize frequency of k by adding x to subarray ALGORITHM STEPS 1 Transform Problem For each nums[i], compute diff = k - nums[i] 2 Group by Diff diff[0]=3, diff[1]=2 diff[2]=0, diff[3]=2 3 Max Subarray Sum For each unique diff value, find max subarray with matching elements (+1) 4 Add Existing k's Count current k values Base count = 1 (index 2) For x=2: indices 1,3 Subarray gain = 2 Total = 1 + 2 = 3 FINAL RESULT Optimal: Add x=2 to [1..3] 1 4 4 4 [1,2,4,2] + 2 on [1..3] = [1, 4, 4, 4] Output 3 OK - Verified Frequency of k=4: 3 Maximum achievable Key Insight: Transform to Maximum Subarray problem: For each element, if we want it to become k, we need to add (k - nums[i]). Group elements by their required diff value. For each group, find the maximum contiguous subarray that can be converted to k, then add the count of elements already equal to k. This gives O(n) solution per unique diff. TutorialsPoint - Maximum Frequency After Subarray Operation | Optimized Enumeration Approach
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