Code Logo

Find Max Number

Published at10 Jan 2026
Easy 26 views
Like11

This problem asks for the largest number in the array. You do not need to sort anything or rearrange the data. You only need to identify which value is bigger than all the others.

The answer is the value itself, not its index. Negative numbers still count normally, so if every number is negative, you return the one that is closest to zero because it is still the largest among them.

For example, if nums = [1,5,3,9,2], the answer is 9. If nums = [-10,-5,-20,-1], the answer is -1 because it is greater than the other negative values. If the array has only one element, that element is automatically the maximum.

So the task is to scan the array and return the single largest value present in it.

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
Recommendation Algorithm Flow for Find Max Number

Solution Approach

The simplest way to solve this is with one pass through the array while tracking the largest value seen so far.

We begin with the first element as the current maximum:

let maxValue = nums[0];

Then we compare every remaining number against it:

for (let i = 1; i < nums.length; i++) {
  if (nums[i] > maxValue) {
    maxValue = nums[i];
  }
}

Whenever we find a larger value, we replace maxValue. By the end of the loop, it holds the biggest number in the array.

The final step is just:

return maxValue;

This runs in O(n) time and uses O(1) extra space.

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;
    }
}