Write a function `findMax(arr)` that returns the largest number in the array without using Math.max.
Problem Statement
Examples
Input: arr = [3, 7, 2, 9, 1]
Output: 9
Explanation: 9 is the largest integer in the array.
Input: arr = [-5, -2, -8]
Output: -2
Explanation: -2 is the maximum value among negative numbers.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Find Maximum in Array, we consider the execution characteristics of JavaScript engines. Write a function `findMax(arr)` that returns the largest number in the array without using Math.max. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (initialize a variable with the first element of the array).
- Implement Logic: Handle state and transformations efficiently (loop through the array and update the variable if a larger value is found).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function findMax(arr) {
return arr.reduce((max, val) => val > max ? val : max, arr[0]);
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.