new class js -advanced
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
function findMax(arr) {
|
||||
// Base case: empty array
|
||||
if (arr.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// Base case: array with one element
|
||||
if (arr.length === 1) {
|
||||
return arr[0];
|
||||
}
|
||||
// Recursive case: return the maximum of the first element and the maximum of the rest of the array
|
||||
const subMax = findMax(arr.slice(1));
|
||||
return arr[0] > subMax ? arr[0] : subMax;
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(findMax([1, 5, 3, 9, 2])); // => 9
|
||||
console.log(findMax([-10, -20, -3, -4])); // => -3
|
||||
console.log(findMax([42])); // => 42
|
||||
console.log(findMax([])); // => null
|
||||
Reference in New Issue
Block a user