Problem Statement
Find the max sequence finder.
findMaxSequence([3, 2, 3, 4, 2, 2, 4]);
findMaxSequence([3, 5, 4, 6, 1, 2, 3, 6, 10, 32]);
findMaxSequence([3, 2, 1]);
Expected Output
[ 2 , 3 , 4 ]
[1, 2, 3, 6, 10, 32]
no
Solution
function findMaxSequence(array, start = -1, end = -1, i = 0, results=[]){ if((array.length == 1) || (array.length == 0)){ return "[ " + array + " ]"; } else if(i >= array.length-1){ if(start != -1){ results.push(array.slice(start, end+1)); } if(results.length > 0){ results.sort( function(a, b){ return a.length < b.length; } ); return "[ " + results[0].toString() + " ]"; }else{ return "no"; } }else if(array[i] < array[i+1]){ if (start == -1){ start = i; } return findMaxSequence(array, start, i+1, ++i, results); }else if(array[i] >= array[i+1]){ if(start != end){ results.push(array.slice(start, end+1)) } return findMaxSequence(array, -1, -1, ++i, results); } } console.log(findMaxSequence([3,2,3,4,2,2,4])); console.log(findMaxSequence([3, 5, 4, 6, 1, 2, 3, 6, 10, 32])); console.log(findMaxSequence([3,2,1])); console.log(findMaxSequence([1])); console.log(findMaxSequence([2, 2, 2, 2])); console.log(findMaxSequence([1, 2, 2, 3, 3, 4]));
Actual output
[ 2,3,4 ] [ 1,2,3,6,10,32 ] no [ 1 ] no [ 1,2 ]
A per the above solution, Did I understand the problem statement? Wrt two elements being equal in an array? Did I handle two equal size sequences correctly?
Can we make the code more elegant? I see lot of nested conditions, which makes it less readable.
Is it an elegant approach of using
results
array? Please let me know, if there is any better approach.
Note: Above problem is pulled from here. Tested on firefox browser, Chrome could not support default argument syntax
[]
\$\endgroup\$[1]
and[]
return 'a sequence', yet[2, 1]
returns"no"
\$\endgroup\$