JavaScript Top-N Numbers: Two Approaches Quiz
Return the N largest numbers from an array (order-not-required), two ways (sort + slice and one-pass min-tracking buffer), plus two companions on heap-style updates and tie-aware quickselect.
Question Bank
Hard
JavaScript
quiz
arrays
sorting
array-manipulation-patterns
344 views
10
Implement topMax(arr, n) using a plain SORT + SLICE: sort a copy descending and slice the first n. The result order does NOT need to match the original array.
Examples
Example 1:
Input: arr = [3, 9, 1, 8, 6, 2, 12, 5], n = 3
Output: [12, 9, 8]
Explanation: Sorted descending = [12, 9, 8, 6, 5, 3, 2, 1]; the first 3 are [12, 9, 8].3 more questions, with full solutions and explanations, are available for premium members.
Upgrade to Premium