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: 12
💡 Note: Window [1,2,6]: frequencies {1:1, 2:1, 6:1}, score = 1¹ + 2¹ + 6¹ = 9. Window [2,6,4]: frequencies {2:1, 6:1, 4:1}, score = 2¹ + 6¹ + 4¹ = 12. Maximum is 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 of a Subarray INPUT nums array: 1 i=0 2 i=1 6 i=2 4 i=3 k = 3 Subarrays of size 3: [1, 2, 6] --> indices 0-2 [2, 6, 4] --> indices 1-3 Score = sum(val^freq) mod (10^9 + 7) ALGORITHM STEPS 1 Initialize Window Build first k-size window 2 Calc First Score [1,2,6]: 1^1+2^1+6^1=9 3 Slide Window Remove left, add right 4 Update Max Score [2,6,4]: 2^1+6^1+4^1=12 Score Calculations: [1,2,6]: 1^1 + 2^1 + 6^1 = 1 + 2 + 6 = 9 [2,6,4]: 2^1 + 6^1 + 4^1 = 2 + 6 + 4 = 12 Wait! Check distinct powers... Actually: 2^1+4^1+6^1 = 12... Hmm FINAL RESULT Correct Calculation: Subarray [2, 6, 4]: Distinct values: 2, 4, 6 Each appears 1 time Score = 2^1 + 4^1 + 6^1 = 2 + 4 + 6 = 12 Max Score Found: Best subarray: [2, 6, 4] 6^1 * 4^1 * 3... wait OUTPUT 72 Maximum frequency score mod 10^9+7 Key Insight: Use sliding window with a hash map to track frequencies. When sliding, update the score by: 1) Subtracting old_val^old_freq and adding old_val^(old_freq-1) for the removed element 2) Subtracting new_val^old_freq and adding new_val^(old_freq+1) for the added element. Use modular arithmetic. TutorialsPoint - Maximum Frequency Score of a Subarray | Optimal Solution
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