Maximum number of set bits count in a K | Function that find Maximum number of set bit appears in a substring of size K . ; Traverse string 1 to k ; Increment count if character is set bit ; Traverse string k + 1 to length of string ; Remove the contribution of the ( i - k ) th character which is no longer in the window ; Add the contribution of the current character ; Update maxCount at for each window of size k ; Return maxCount ; Driver code
function maxSetBitCount ( s , k ) { var maxCount = 0 , n = s . length ; var count = 0 ; for ( var i = 0 ; i < k ; i ++ ) { if ( s [ i ] == ' ' ) count ++ ; } maxCount = count ; for ( var i = k ; i < n ; i ++ ) { if ( s [ i - k ] == ' ' ) count -- ; if ( s [ i ] == ' ' ) count ++ ; maxCount = Math . max ( maxCount , count ) ; } return maxCount ; } var s = " " ; var k = 3 ; document . write ( maxSetBitCount ( s , k ) ) ;