Tell us what’s happening:
Both of the codes below pass all the tests, but which one will perform faster?
In the first case, I sort the four given arrays in arr
in a descending manner and just push the first element of each of the arrays into a separate array (res
).
In the second case, I traverse each of the sub-arrays in arr
, find the highest element from them manually and push them to the new array (res
).
Your code so far
Sorting the array approach
function largestOfFour(arr) {
// You can do this!
var res = [];
for (var i = 0; i < arr.length; i++) {
arr[i].sort(function(a, b) {
return b - a;
});
res.push(arr[i][0]);
}
return res;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Manual iterative approach:
function largestOfFour(arr) {
// You can do this!
var res = [];
for (var i = 0; i < arr.length; i++) {
var highestNum = Number.MIN_VALUE;
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > highestNum) highestNum = arr[i][j];
}
res.push(highestNum);
}
return res;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0
.
Link to the challenge: