I’m trying to solve some ‘hackerrank.com’ coding challenges. I’m stuck on this one:
You will be given an array of integers arr and a single integer k. You must create an array arr' of length k from elements of arr such that its unfairness is minimized.
Unfairness is defined as max(arr') - min(arr')
The function should return the minimum possible unfairness
My code works fine for the majority of test cases. However, in three of those test cases – the ones where the size of arr and k is particularly huge – fail due to an excession of the given time limit.
How can I optimize the performance of my code? Thanks in advance
function maxMin(k, arr) {
// create array to push unfairness values to
var unfairnesses = [];
// sort given array in ascending order
arr.sort(function(a, b) {
return a - b;
});
// loop over sorted array
for(var i = 0; i < arr.length - k + 1; i++) {
// get array with the length of k at position i
var tempArr = arr.slice(i, i + k);
// determine Max and Min of the sliced array
var tempArrMax = Math.max(...tempArr);
var tempArrMin = Math.min(...tempArr);
// get unfairness of the sliced array
var thisUnfairness = tempArrMax - tempArrMin;
// push sliced-array-unfairness to unfairnesses array
unfairnesses.push(thisUnfairness);
}
// return minimal value of unfairnesses array
return Math.min(...unfairnesses);
}
Advertisement
Answer
The two first steps could be:
- Your array is sorted. Thus there’s no need to use
Math.maxandMath.min– the first element of a slice is the smallest, the last is the largest. - When you eliminate
Math.maxandMath.mincalls, you can removeArray.prototype.slicecall. Then you’re left with a sort and a single pass over the array.