Skip to content

Latest commit

 

History

History

2524

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

  • For example, the frequency score of the array [5,4,5,7,4,4] is (43 + 52 + 71) modulo (109 + 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 <= 105
  • 1 <= nums[i] <= 106

Companies: PayPal

Related Topics:
Array, Hash Table, Math, Sliding Window

Solution 1. Fixed-length Sliding Window

// OJ: https://leetcode.com/problems/maximum-frequency-score-of-a-subarray
// Author: github.com/lzl124631x
// Time: O(N * sqrt(N))
// Space: O(N)
class Solution {
public:
    int maxFrequencyScore(vector<int>& A, int k) {
        long N = A.size(), ans = 0, sum = 0, mod = 1e9 + 7;
        unordered_map<int, int> cnt;
        auto score = [&](long base, long e) {
            if (e == 0) return 0L;
            long ans = 1;
            while (e) {
                if (e & 1) ans = ans * base % mod;
                base = base * base % mod;
                e >>= 1;
            }
            return ans;
        };
        for (int i = 0; i < N; ++i) {
            int a = A[i], fa = cnt[A[i]]++;
            sum = (sum - score(a, fa) + score(a, fa + 1) + mod) % mod;
            if (i - k >= 0) {
                int b = A[i - k], fb = cnt[A[i - k]]--;
                sum = (sum - score(b, fb) + score(b, fb - 1) + mod) % mod;
            }
            if (i >= k - 1) ans = max(ans, sum);
        }
        return ans;
    }
};