Maximize length of longest non | Function to find the length of the longest non - decreasing array that can be generated ; Stores the length of the longest non - decreasing array that can be generated from the array ; Stores index of start poleter ; Stores index of end poleter ; Stores previously inserted element leto the new array ; Traverse the array ; If A [ start ] is less than or equal to A [ end ] ; If no element inserted leto the newly generated array ; Update prev ; Update res ; Update start ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ end ] is greater than A [ start ] ; If no element inserted leto the newly generated array ; Update prev ; Update res ; Update end ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; Driver Code ; Function call
function findLongestNonDecreasing ( A , N ) { let res = 0 ; let start = 0 ; let end = N - 1 ; let prev = - 1 ; while ( start <= end ) { if ( A [ start ] <= A [ end ] ) { if ( prev == - 1 ) { prev = A [ start ] ; res ++ ; start ++ ; } else { if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else { break ; } } } else { if ( prev == - 1 ) { prev = A [ end ] ; res ++ ; end -- ; } else { if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else { break ; } } } } return res ; } let A = [ 1 , 1 , 3 , 5 , 4 , 3 , 6 , 2 , 1 ] ; let N = A . length ; document . write ( findLongestNonDecreasing ( A , N ) ) ;