|
| 1 | +/** |
| 2 | + * 3318. Find X-Sum of All K-Long Subarrays I |
| 3 | + * https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given an array nums of n integers and two integers k and x. |
| 7 | + * |
| 8 | + * The x-sum of an array is calculated by the following procedure: |
| 9 | + * - Count the occurrences of all elements in the array. |
| 10 | + * - Keep only the occurrences of the top x most frequent elements. If two elements |
| 11 | + * have the same number of occurrences, the element with the bigger value is |
| 12 | + * considered more frequent. |
| 13 | + * - Calculate the sum of the resulting array. |
| 14 | + * |
| 15 | + * Note that if an array has less than x distinct elements, its x-sum is the sum of the array. |
| 16 | + * |
| 17 | + Return an integer array answer of length n - k + 1 where answer[i] is the x-sum of the |
| 18 | + subarray nums[i..i + k - 1]. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums |
| 23 | + * @param {number} k |
| 24 | + * @param {number} x |
| 25 | + * @return {number[]} |
| 26 | + */ |
| 27 | +var findXSum = function(nums, k, x) { |
| 28 | + const n = nums.length; |
| 29 | + const result = []; |
| 30 | + |
| 31 | + for (let i = 0; i <= n - k; i++) { |
| 32 | + const subarray = nums.slice(i, i + k); |
| 33 | + result.push(helper(subarray)); |
| 34 | + } |
| 35 | + |
| 36 | + return result; |
| 37 | + |
| 38 | + function helper(subarray) { |
| 39 | + const frequency = new Map(); |
| 40 | + |
| 41 | + for (const num of subarray) { |
| 42 | + frequency.set(num, (frequency.get(num) || 0) + 1); |
| 43 | + } |
| 44 | + |
| 45 | + const elements = Array.from(frequency.entries()); |
| 46 | + elements.sort((a, b) => { |
| 47 | + if (a[1] !== b[1]) return b[1] - a[1]; |
| 48 | + return b[0] - a[0]; |
| 49 | + }); |
| 50 | + |
| 51 | + const topX = elements.slice(0, x); |
| 52 | + let sum = 0; |
| 53 | + |
| 54 | + for (const [value, count] of topX) { |
| 55 | + sum += value * count; |
| 56 | + } |
| 57 | + |
| 58 | + return sum; |
| 59 | + } |
| 60 | +}; |
0 commit comments