Maximum Frequency After Subarray Operation Problem
Description
LeetCode Problem 3434.
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]where0 <= i <= j <= n - 1. - Select an integer
xand addxto all the elements innums[i..j].
Find the maximum frequency of the value k after the operation.
Example 1:
Input: nums = [1,2,3,4,5,6], k = 1
Output: 2
Explanation:
After adding -5 to nums[2..5], 1 has a frequency of 2 in [1, 2, -2, -1, 0, 1].
Example 2:
Input: nums = [10,2,3,4,5,5,4,3,2,2], k = 10
Output: 4
Explanation:
After adding 8 to nums[1..9], 10 has a frequency of 4 in [10, 10, 11, 12, 13, 13, 12, 11, 10, 10].
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 501 <= k <= 50
Solution
Approach: Kadane Over Each Value
Adding the same x to a subarray turns all of its elements equal to k - x into k, while the elements that were k inside it stop being k. So for one chosen value v != k, the gain of a subarray is (the number of v in it) minus (the number of k in it). The answer is the total count of k plus the best gain over all v (at least 0, using x = 0).
That is a maximum-subarray problem, and it can be run for all values in one pass. For each value v keep d[v], the best gain of a subarray ending at the latest v, and the number of k seen at that point. When another v arrives, the ks in between subtract from d[v]; clamp at 0 (start fresh) and add one. Track the maximum d[v].
Complexity: O(n) time and O(A) space, where A = 50 is the largest value.
class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
# d[v]: best (count of v - count of k) over subarrays ending at the last v
d = [0] * 51
last = [0] * 51 # number of k's seen when v was last seen
ck = 0
best = 0
for a in nums:
if a == k:
ck += 1
else:
d[a] = max(d[a] - (ck - last[a]), 0) + 1
last[a] = ck
best = max(best, d[a])
return ck + best