Member-only story
Leetcode 1471: The k Strongest Values in an Array
2 min readJun 11, 2020
In this Leetcode problem, we are given an array arr
and an integer k
, we want to figure out what are the k values v
in the array such that |v — m|
is maximum with m
the median value in the array.
Solution
A simple way to resolve is if to first think about sorting the array. Indeed, it seems much easier to solve the problem once the array is sorted. There could be more efficient method relying a count sort or bucketing to find the median and find the k strongest values, but I took a simpler approach.
- Sort the array
- Set
med = arr[(n-1) / 2];
- Keep 2 pointers
low
andhigh
. They should point to the index of next potential strongest values. At the start,low = 0
, andhigh = n — 1
point to the only 2 values that can be the strongest. - At each iteration, find which of
arr[low]
orarr[high]
is the strongest, ifarr[low]
is the strongest, move low to the next valuelow + 1
, ifarr[high]
is the strongest, move high to the next valuehigh — 1
. Do thatk
times until the arrayres
is full.
class Solution {
public int[] getStrongest(int[] arr, int k) {
Arrays.sort(arr);
int n = arr.length;
int med = arr[(n-1) / 2];
int[] res = new int[k];
int low = 0;
int high = n …