Find Max Number
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: The maximum value in [1, 5, 3, 9, 2] is 9
Example 2: The maximum value in [-10, -5, -20, -1] is -1
Example 3: With a single element, that element is the maximum
Algorithm Flow
Solution Approach
Iterate through the array while tracking the largest value seen so far.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
