Explorer
JavaScript

Write a function `findMax(arr)` that returns the largest number in the array without using Math.max.

Problem Statement

<p>Write a function <code>findMax(arr)</code> that returns the largest number in the array without using Math.max.</p>

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

šŸ’” Hint 1: Initialize a variable with the first element of the array. šŸ’” Hint 2: Loop through the array and update the variable if a larger value is found. šŸ’” Hint 3: Use reduce: return arr.reduce((max, val) => val > max ? val : max, arr[0]);

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (initialize a variable with the first element of the array).
  3. Implement Logic: Handle state and transformations efficiently (loop through the array and update the variable if a larger value is found).
  4. 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

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

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.

Find Maximum in Array

Easy

Write a function findMax(arr) that returns the largest number in the array without using Math.max.

Example Scenarios
1Example 1
Input: arr = [3, 7, 2, 9, 1]
Output: 9
Explanation:

9 is the largest integer in the array.

2Example 2
Input: arr = [-5, -2, -8]
Output: -2
Explanation:

-2 is the maximum value among negative numbers.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[9,-2,42]