Maximum Frequency Score of a Subarray — LeetCode 2524 Python Solution

HardLeetCode PremiumStackArrayHash TableMathSliding Window
Problem
#2524
Reading time
3 min

The problem

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 109 + 7.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2524. Maximum Frequency Score of a Subarray is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2524. Maximum Frequency Score of a Subarray?
LeetCode 2524. Maximum Frequency Score of a Subarray is rated Hard on LeetCode.
What is the time complexity of LeetCode 2524. Maximum Frequency Score of a Subarray?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2524. Maximum Frequency Score of a Subarray?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2524. Maximum Frequency Score of a Subarray cover?
LeetCode 2524. Maximum Frequency Score of a Subarray is tagged Stack, Array, Hash Table, Math and Sliding Window on LeetCode.
Is LeetCode 2524. Maximum Frequency Score of a Subarray a premium problem?
Yes. LeetCode 2524. Maximum Frequency Score of a Subarray is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview