DEV Community

Discussion on: Largest no. in Array using Recursion

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

It is not very helpful to check each call to see if arr is an array, if the array is empty, or if it only has one value.

"use strict";

const findMax = ( arr ) => {
  const fmax = ( arr ) => {
    if ( arr[ idx ] > max ) 
      max = arr[ idx ]
    if ( idx < arr.length ) {
      idx++;
      fmax( arr )
    }
    return max
  }
  if ( !Array.isArray( arr ) ) throw 'Not an array'
  if ( arr.length === 0 ) return undefined
  if ( arr.length === 1 ) return arr[ 0 ]
  let idx = 0
  let max = arr[ idx ]
  max = fmax( arr )
  return max
}
console.log ( findMax ( [ -10,-9 ] ) )
console.log ( findMax ( [ 1,9,100,28,78,10 ] ) )
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah for recursion approach it's not good

Collapse
 
frankwisniewski profile image
Frank Wisniewski

in this case for loop would be more appropriate...

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Actually it is a question which is asked in an interview so i tried to solve it later because I was not able to solve it at the time of interview 😂😂

Thread Thread
 
fjones profile image
FJones

Okay, yeah, I would've refused that answer with "why on Earth would you do that?".

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah it won't make a difference Because they already rejected 😂😂