[LeetCode] Maximum Frequency Score of a Subarray

2524. Maximum Frequency Score of a Subarray

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int maxFrequencyScore(vector<int>& nums, int k) {
unordered_map<long long, vector<long long>> mp;
long long res = 0, now = 0, mod = 1e9 + 7;
for(int i = 0; i < nums.size(); i++) {
if(i >= k) {
now = (now - mp[nums[i-k]].back() + mod) % mod;
mp[nums[i-k]].pop_back();
if(mp[nums[i-k]].size()) {
now = (now + mp[nums[i-k]].back()) % mod;
}
}
if(mp[nums[i]].size() == 0) {
mp[nums[i]].push_back(nums[i]);
now = (now + nums[i]) % mod;
} else {
now = (now - mp[nums[i]].back() + mod) % mod;
mp[nums[i]].push_back(mp[nums[i]].back() * nums[i] % mod);
now = (now + mp[nums[i]].back()) % mod;
}
if(i + 1 >= k) res = max(res, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/30/PS/LeetCode/maximum-frequency-score-of-a-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.