Learner Level
Implement the method findMax that takes an array of integers and returns the largest (maximum) value in the array.
Write a function that receives an array of integers and returns the largest number present in the array. The function should compare all elements and return the maximum value found.
Example 1
Input
nums (int[]) =
[1, 4, 2, 9, 7]len (int) =
5Returns (int)
9Example 2
Input
nums (int[]) =
[-10, -5, -3]len (int) =
3Returns (int)
-3Example 3
Input
nums (int[]) =
[0, 0, 0, 0]len (int) =
4Returns (int)
0Example 4
Input
nums (int[]) =
[5]len (int) =
1Returns (int)
5To find the maximum number in an array:
-
Initialize a Max Variable
Set a variable to hold the current maximum value (e.g., the first element of the array). -
Iterate Through the Array
Loop over the array starting from the second element. -
Compare and Update
If the current element is greater than the stored maximum, update the maximum. -
Return the Result
After the loop ends, return the maximum value found.
Pseudocode:
Function findMax(nums, len):
max ← nums[0]
For i from 1 to len - 1:
If nums[i] > max:
max ← nums[i]
Return max
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run