Maximum Frequency Score of a Subarray - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,6,4], k = 3
Output: 72
💡 Note: Window [1,2,6]: score = 1¹ + 2¹ + 6¹ = 9. Window [2,6,4]: score = 2¹ + 6¹ + 4¹ = 12. Maximum is 12. Wait, let me recalculate: actually we need frequency powers. [2,6,4] has frequencies {2:1, 6:1, 4:1}, so score = 2¹ + 6¹ + 4¹ = 12.
Example 2 — Repeated Elements
$ Input: nums = [5,4,5,7,4,4], k = 6
Output: 96
💡 Note: Only one window of size 6: [5,4,5,7,4,4]. Frequencies: {5:2, 4:3, 7:1}. Score = 5² + 4³ + 7¹ = 25 + 64 + 7 = 96.
Example 3 — Small Window
$ Input: nums = [2,2], k = 1
Output: 2
💡 Note: Two windows: [2] and [2]. Each has frequency {2:1}, score = 2¹ = 2. Maximum is 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum Frequency Score: Find Best Subarray of Size k54574Array: [5,4,5,7,4], k=3Window 1: [5,4,5]Frequencies: {5:2, 4:1}Score: 5² + 4¹ = 25 + 4 = 29Window 2: [4,5,7]Frequencies: {4:1, 5:1, 7:1}Score: 4¹ + 5¹ + 7¹ = 16Continue for Window 3: [5,7,4]...Frequencies: {5:1, 7:1, 4:1} → Score: 16Maximum Score Found: 29Optimal window has highest frequency score
Understanding the Visualization
1
Input Array
Array with elements and window size k
2
Calculate Frequencies
Count occurrences in each subarray
3
Compute Score
Sum of value^frequency for each unique element
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently calculate frequency scores for all k-sized subarrays and track the maximum
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
28.5K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen