#1471

The k Strongest Values in an Array

specialist · 690 · lc medium +30 · verified · 62.6% accepted · 724 likes · top 64%

Description

Given an integer array arr and an integer k, define the center m as the element at position ((n-1)/2) in the sorted version of arr (0-indexed). An element arr[i] is stronger than arr[j] when |arr[i] - m| > |arr[j] - m|, or when those distances are equal but arr[i] > arr[j].

Return any list of the k strongest elements.

Example 1:

Input: arr = [1,2,3,4,5], k = 2
Output: [5,1]
Explanation: Centre is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.

Example 2:

Input: arr = [1,1,3,5,5], k = 2
Output: [5,5]
Explanation: Centre is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].

Example 3:

Input: arr = [6,7,11,7,6,8], k = 5
Output: [11,8,6,6,7]
Explanation: Centre is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
Any permutation of [11,8,6,6,7] is accepted.

Code

1
2
3