Sum of Weighted Modes in Subarrays
You are given an integer array nums of size n and an integer k.
For every contiguous subarray of size k, define:
- The mode as the element that appears most frequently in that subarray.
- If multiple elements have the same highest frequency, choose the smallest among them.
- The weight of that subarray as: mode × frequency of mode
Return the total sum of weights for all subarrays of length k.
A subarray is a contiguous sequence of elements within the array.
Example 1:
Input: nums = [2, 1, 2, 1, 2], k = 3
Output: 10
Explanation:
- [2, 1, 2] → mode = 2 (appears 2 times) → weight = 2 × 2 = 4
- [1, 2, 1] → mode = 1 (appears 2 times) → weight = 1 × 2 = 2
- [2, 1, 2] → mode = 2 (appears 2 times) → weight = 2 × 2 = 4
Total = 4 + 2 + 4 = 10
Example 2:
Input: nums = [5, 5, 6, 6, 6], k = 4
Output: 28
Explanation:
Subarrays of size 4 are:
- [5, 5, 6, 6] → tie (5 and 6 appear twice), choose smaller → mode = 5 → weight = 5 × 2 = 10
- [5, 6, 6, 6] → mode = 6 (appears 3 times) → weight = 6 × 3 = 18
Total = 10 + 18 = 28
Now Your Turn!
Pick the correct output for the given inputInput: nums = [3, 4, 3, 4], k = 3
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ n = nums.length ≤ 105
- 1 ≤ nums[i] ≤ 105
- 1 ≤ k ≤ n
- The array contains only positive integers.
- The answer fits in a 64-bit signed integer.