Count the number of times graph crosses X | Function to to count the number of times the graph crosses the x - axis . ; Iterate over the steps array ; Update the previous level and current level by value given in the steps array ; Condition to check that the graph crosses the origin . ; Driver Code
function times ( steps , n ) { let current_level = 0 ; let previous_level = 0 ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { previous_level = current_level ; current_level = current_level + steps [ i ] ; if ( ( previous_level < 0 && current_level >= 0 ) || ( previous_level > 0 && current_level <= 0 ) ) { count ++ ; } } return count ; } let steps = [ 1 , - 1 , 0 , 0 , 1 , 1 , - 3 , 2 ] ; let n = steps . length ; document . write ( times ( steps , n ) ) ;