The k Strongest Values in an Array

In this problem, you are given an array of integers arr and an integer k. Your goal is to return the k strongest values in the array based on their difference with the median of the array. The stronger value is the one with the larger absolute difference with the median, or if the differences are equal, the larger number.

Here is a Python solution using the sorting capability of Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from typing import List

class Solution:
    def getStrongest(self, arr: List[int], k: int) -> List[int]:
        arr.sort()
        m = arr[(len(arr) - 1) // 2]  # Find the median

        # Sort array based on the "strength"
        arr.sort(key = lambda x: (abs(x - m), x), reverse = True)

        # Return the first k elements from the sorted array
        return arr[:k]

This solution first sorts the array to find the median, which is the element in the middle of the sorted array. Then, it sorts the array again based on the “strength” of each element, defined as its absolute difference from the median. In case of a tie, the element with the higher value is considered stronger. The sort operation is done in descending order (reverse = True) to get the strongest elements first. Finally, the solution returns the first k elements from the sorted array, which are the k strongest elements.