Maximum number of set bits count in a K | Java 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 Program
import java . util . * ; class GFG { static int maxSetBitCount ( String s , int k ) { int maxCount = 0 , n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s . charAt ( i ) == '1' ) count ++ ; } maxCount = count ; for ( int i = k ; i < n ; i ++ ) { if ( s . charAt ( i - k ) == '1' ) count -- ; if ( s . charAt ( i ) == '1' ) count ++ ; maxCount = Math . max ( maxCount , count ) ; } return maxCount ; } public static void main ( String [ ] args ) { String s = "100111010" ; int k = 3 ; System . out . println ( maxSetBitCount ( s , k ) ) ; } }