Count the number of times a Bulb switches its state | Function to find the number of times a bulb switches its state ; Count of 1 s ; Traverse the array ; Update count of 1 s ; Update the status of bulb ; Traverse the array Q [ ] ; Stores previous state of the bulb ; Toggle the switch and update count of 1 s ; If the bulb switches state ; Return count ; Input ; Queries ; Function call to find number of times the bulb toggles
function solve ( A , n , Q , q ) { var one = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( A [ i ] == 1 ) one ++ ; var glows = 0 , count = 0 ; if ( one >= Math . ceil ( n / 2 ) ) glows = 1 ; for ( var i = 0 ; i < q ; i ++ ) { var prev = glows ; if ( A [ Q [ i ] - 1 ] == 1 ) one -- ; if ( A [ Q [ i ] - 1 ] == 0 ) one ++ ; A [ Q [ i ] - 1 ] ^= 1 ; if ( one >= Math . ceil ( n / 2.0 ) ) { glows = 1 ; } else { glows = 0 ; } if ( prev != glows ) count ++ ; } return count ; } var n = 3 ; var arr = [ 1 , 1 , 0 ] ; var q = 3 ; var Q = [ 3 , 2 , 1 ] ; document . write ( solve ( arr , n , Q , q ) ) ;