-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-4_Find_the_Maximum_Number.js
More file actions
33 lines (24 loc) · 1.42 KB
/
Problem-4_Find_the_Maximum_Number.js
File metadata and controls
33 lines (24 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Problem-4_Find_the_Maximum_Number with Solution, Explanation, Verification, and Execution:
// To find the maximum number in an array, we can implement the Solution like below:
// -------------------------------------------------------------------
function findMax(nums) {
if (nums.length === 0) return null;
return Math.max(...nums);
}
let nums = [5, 1, 9, 3];
console.log(findMax(nums));
// Explanation:
// ---------------
// Normally, Math.max() takes numbers as arguments like Math.max(5, 1, 9, 3). But it doesn't work directly on arrays like Math.max([5, 1, 9, 3]). The spread operator (...) is useful here and it will convert the array ([5, 1, 9, 3]) into a sequence of number (5, 1, 9, 3). Now, if we put that sequence of number into a variable and call the function with the variable as argument, we will get our desired output as the maximum number of that array.
// Verification:
// ----------------
// function findMax(nums = [5, 1, 9, 3]) {
// if (nums.length === 0) return null;
// return Math.max(...nums);
// }
// let nums = [5, 1, 9, 3];
// console.log(findMax(nums));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-4_Find_the_Maximum_Number.js'
// Output (In the directory in IDE environment with node.js installed): 9