Find Maximum
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
Algorithm Flow

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
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;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
