Solution from Mark Metzger to the Project
Snippet A (sort-based)
var max = array.sort.pop()
Snippet B (linear loop)
var max = 0
for (i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i]
}
}
Short answerSnippet B (the linear loop) is faster. It scans the array once, so it runs in O(n) time. Snippet A relies on sorting, which costs O(n log n) — it does strictly more work to find a single value.
Why the loop wins• Complexity: Sorting arranges every element relative to every other (O(n log n)). Finding the maximum only requires comparing each element to the current best, which is a single O(n) pass.
• Less work, less memory: The loop never reorders data and allocates nothing extra. Sorting touches and moves elements many times and (depending on the engine) may use additional memory.
• Side effects: Array.sort() mutates the original array in place, which the loop does not.
Correctness caveats (both snippets are buggy as written)• Snippet A: array.sort is missing its parentheses, so it is a function reference, not a call — .pop() on it does not return the maximum. Even when written correctly as array.sort().pop(), JavaScript’s default sort compares values as strings, so it gives wrong results for numbers (e.g. 10 sorts before 9) unless a numeric comparator is passed.
• Snippet B: Initialising max = 0 is wrong if every value is negative (it would return 0). A safer start is max = array[0] or -Infinity. Also, i is not declared with let/var, creating an implicit global.
ConclusionFor finding a maximum, the single-pass loop is the right approach: O(n) beats O(n log n). In practice you would simply use Math.max(...array) for the same linear cost with cleaner code.