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
def maxSetBitCount ( s , k ) : NEW_LINE INDENT maxCount = 0 NEW_LINE n = len ( s ) NEW_LINE count = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT maxCount = count NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT if ( s [ i - k ] == '1' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT maxCount = max ( maxCount , count ) NEW_LINE DEDENT return maxCount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "100111010" NEW_LINE k = 3 NEW_LINE print ( maxSetBitCount ( s , k ) ) NEW_LINE DEDENT