Maximum number of set bits count in a K | C ++ program to find the maximum set bits in a substring of size 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSetBitCount ( string s , int k ) { int maxCount = 0 , n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s [ i ] == '1' ) count ++ ; } maxCount = count ; for ( int i = k ; i < n ; i ++ ) { if ( s [ i - k ] == '1' ) count -- ; if ( s [ i ] == '1' ) count ++ ; maxCount = max ( maxCount , count ) ; } return maxCount ; } int main ( ) { string s = "100111010" ; int k = 3 ; cout << ( maxSetBitCount ( s , k ) ) ; return 0 ; }