Maximum Frequency Score of a Subarray Problem
Description
LeetCode Problem 2524.
You are given an integer array nums and a positive integer k.
The frequency score of an array is the sum of the distinct values in the array raised to the power of their frequencies, taking the sum modulo 10^9 + 7.
- For example, the frequency score of the array
[5,4,5,7,4,4]is(4^3 + 5^2 + 7^1) modulo (10^9 + 7) = 96.
Return the maximum frequency score of a subarray of size k in nums. You should maximize the value under the modulo and not the actual value.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,1,1,2,1,2], k = 3
Output: 5
Explanation: The subarray [2,1,2] has a frequency score equal to 5. It can be shown that it is the maximum frequency score we can have.
Example 2:
Input: nums = [1,1,1,1,1,1], k = 4
Output: 1
Explanation: All the subarrays of length 4 have a frequency score equal to 1.
Constraints:
1 <= k <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Sliding Window + Fast Power
The score of a window is the sum of v^cnt[v] over its distinct values, modulo 10^9 + 7. Compute it for the first window, then slide by one position. When an element b enters and a leaves (and a != b), only two terms change:
bgoes fromb^ctob^(c+1), so add(b - 1) * b^c; ifbwas absent, addb.agoes froma^ctoa^(c-1), so subtract(a - 1) * a^(c-1); ifcwas 1, subtracta.
Powers are computed with fast exponentiation. Keep the maximum score over all windows.
Complexity: O(n log n) time and O(n) space, where n is the length of nums.
from collections import Counter
class Solution:
def maxFrequencyScore(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
cnt = Counter(nums[:k])
ans = cur = sum(pow(k, v, mod) for k, v in cnt.items()) % mod
i = k
while i < len(nums):
a, b = nums[i - k], nums[i]
if a != b:
cur += (b - 1) * pow(b, cnt[b], mod) if cnt[b] else b
cur -= (a - 1) * pow(a, cnt[a] - 1, mod) if cnt[a] > 1 else a
cur %= mod
cnt[b] += 1
cnt[a] -= 1
ans = max(ans, cur)
i += 1
return ans