Code Logo

Find Maximum

Published at24 Jul 2026
TypeScript Data Structures Easy 0 views
Like0

Write a TypeScript function that finds the maximum number in an array of integers. Do not use Math.max() — implement the logic manually with a loop.

Initialize a variable with the first element. Loop through the rest of the array. If a larger value is found, update the maximum. Return the maximum value at the end.

Edge cases include arrays with a single element, negative numbers, and all equal values. For an empty array, return 0 or handle as needed.

Finding the maximum value in an array is a fundamental algorithm that teaches array traversal and comparison logic. The algorithm works by keeping a running maximum and updating it whenever a larger value is encountered.

TypeScript's type system enforces that the array contains only numbers, preventing type errors at compile time. The function signature `maxNumber(nums: number[]): number` clearly documents the expected input and output types, making the code self-documenting.

For empty arrays, returning 0 is a simple convention. Alternative approaches include returning -Infinity or throwing an error. The manual loop approach is O(n) time with O(1) space.

The function handles all numeric edge cases including negative numbers (e.g., [-5,-2,-8,-1] correctly returns -1) and arrays with equal values. TypeScript's type annotations provide compile-time safety for parameter and return types.

Example Input & Output

Example 1
Input
[-5,-2,-8,-1]
Output
-1
Example 2
Input
[]
Output
0
Example 3
Input
[3,7,2,9,1]
Output
9
Example 4
Input
[5]
Output
5
Example 5
Input
[1,1,1]
Output
1

Algorithm Flow

Recommendation Algorithm Flow for Find Maximum
Recommendation Algorithm Flow for Find Maximum

Solution Approach

Check if the array is empty and return 0 for empty. Initialize max = nums[0]. Loop from index 1 to nums.length - 1. If nums[i] > max, update max. Return max.

The time complexity is O(n). Space complexity is O(1).

Best Answers

typescript - Approach 1
function maxNumber(nums: number[]): number {
    if (nums.length === 0) return 0;
    var max = nums[0];
    for (var i = 1; i < nums.length; i++) {
        if (nums[i] > max) max = nums[i];
    }
    return max;
}