Code Logo

Find Max Number

Published at10 Jan 2026
1D Array Easy 43 views
Like11

Given an array of integers, find the maximum element and return it. If the array is empty, return 0.

For example, the maximum in [3, 7, 2, 9, 5] is 9. In [-5, -2, -10] it is -2 (the least negative). In [100] it is 100. An empty array returns 0. All equal values [5, 5, 5] return 5.

Finding the maximum is the mirror of finding the minimum and uses the same linear scan pattern. It is used in data analysis (highest score, peak value), algorithm design (tournament selection), and everyday computing (finding the largest file, the most expensive item).

The solution initializes max to the first element, iterates through the remaining elements, and updates max whenever a larger value is encountered. After the loop, return max. This runs in O(n) time with O(1) space.

Edge cases include an empty array (return 0), a single element (return it), all equal values (return that value), and negative numbers (the maximum is correctly identified as the least negative).

Example Input & Output

Example 1
Input
nums = [1, 5, 3, 9, 2]
Output
9
Explanation

Example 1: The maximum value in [1, 5, 3, 9, 2] is 9

Example 2
Input
nums = [-10, -5, -20, -1]
Output
-1
Explanation

Example 2: The maximum value in [-10, -5, -20, -1] is -1

Example 3
Input
nums = [42]
Output
42
Explanation

Example 3: With a single element, that element is the maximum

Algorithm Flow

Recommendation Algorithm Flow for Find Max Number

Solution Approach

Iterate through the array while tracking the largest value seen so far.

function findMax(arr)
  if arr is empty then return 0
  max = arr[0]
  for i = 1 to length(arr) - 1
    if arr[i] > max then max = arr[i]
  return max

Handle the empty case by returning 0 immediately. Initialize max to the first element. Loop through the remaining elements; if any element exceeds the current max, update max. After examining all elements, return the maximum found.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int find_max_number(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int max = nums[0];
        for (int num : nums) {
            if (num > max) max = num;
        }
        return max;
    }
}