Coding problem · Easy · Basics
Find the Maximum
Easy Algorithms & data structures
Return the largest number in the non-empty array nums. Try it without built-in max functions first.
Example 1
Input: nums = [3,9,2,7] Output: 9
Example 2
Input: nums = [-4,-2,-8] Output: -2
Hints
Hint 1
Start with the first element as the best so far, then compare each other element with it.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Assume the first element is the maximum, then replace it whenever a bigger element appears. Starting from 0 would be wrong for all-negative arrays.
Reference solution
function findMax(nums) {
let best = nums[0];
for (const n of nums) if (n > best) best = n;
return best;
}
function findMax(nums: number[]): number {
let best = nums[0];
for (const n of nums) if (n > best) best = n;
return best;
}
def find_max(nums: list[int]) -> int:
best = nums[0]
for n in nums:
if n > best:
best = n
return best
<?php
function findMax(array $nums): int
{
$best = $nums[0];
foreach ($nums as $n) {
if ($n > $best) {
$best = $n;
}
}
return $best;
}
class Solution {
public int findMax(int[] nums) {
int best = nums[0];
for (int n : nums) if (n > best) best = n;
return best;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy