Ctrl K

Top-Frequency Window Sums

Easy
You are given an array values of length n and two integers width and top. For any segment of the array, define its **frequency sum** as follows: 1. Count how many times each value occurs. 2. Rank the distinct values by frequency; on a tie, the larger value ranks higher. 3. Keep only the top highest-ranked values (all of their occurrences) and add up the kept elements. If the segment has fewer than top distinct values, its frequency sum is simply the sum of the segment. Return an array of n - width + 1 numbers whose i-th entry is the frequency sum of values[i..i + width - 1].
Example 1
values=[4, 4, 1, 7, 1, 4], width=4, top=1 → [8, 2, 2]

Windows: [4,4,1,7] — 4 is most frequent, sum 8; [4,1,7,1] — 1 is most frequent, sum 2; [1,7,1,4] — again 1, sum 2.

Example 2
values=[2, 9, 2, 9, 5], width=5, top=2 → [22]

There is a single window. 2 and 9 occur twice each, 5 once. Keeping two groups gives 2 + 2 + 9 + 9 = 22.

Example 3
values=[3, 6, 8], width=2, top=1 → [6, 8]

In each window every number occurs once, so the larger one wins: 6, then 8.

Constraints
  • 1 ≤ n = values.length ≤ 50
  • 1 ≤ values[i] ≤ 50
  • 1 ≤ top ≤ width ≤ n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMoving Window Median HardNarrowest Range Touching Every List HardCheapest Cut With Close Starts HardTop Frequency Window Sums: Large Input HardA Level Stretch of Fence Medium
loading Python…
Input
values=[4, 4, 1, 7, 1, 4], width=4, top=1
Expected
[8, 2, 2]

Run checks the first 3 tests in your browser. Submit checks all 186 tests on the server, hidden ones included.