Longest alternating ( positive and negative ) subarray starting at every index | JavaScript program to find longest alternating subarray starting from every index . ; Fill count [ ] from end . ; Prlet result ; Driver code
function longestAlternating ( arr , n ) { let count = new Array ( n ) ; count [ n - 1 ] = 1 ; for ( let i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] * arr [ i + 1 ] < 0 ) count [ i ] = count [ i + 1 ] + 1 ; else count [ i ] = 1 ; } for ( let i = 0 ; i < n ; i ++ ) document . write ( count [ i ] + " " ) ; } let a = [ - 5 , - 1 , - 1 , 2 , - 2 , - 3 ] ; let n = a . length ; longestAlternating ( a , n ) ;