Maximum number of Perfect Numbers present in a subarray of size K | Function to check a number is Perfect Number or not ; Stores sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to N ; Function to return maximum sum of a subarray of size K ; If k is greater than N ; Compute sum of first window of size K ; Compute sums of remaining windows by removing first element of previous window and adding last element of current window ; Return the answer ; Function to find all the perfect numbers in the array ; The given array is converted into binary array ; Driver Code
function isPerfect ( N ) { let sum = 1 ; for ( let i = 2 ; i < Math . sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { sum += i ; } else { sum += i + N / i ; } } } if ( sum == N && N != 1 ) return 1 ; return 0 ; } function maxSum ( arr , N , K ) { if ( N < K ) { document . write ( " " ) ; return - 1 ; } let res = 0 ; for ( let i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } let curr_sum = res ; for ( let i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = Math . max ( res , curr_sum ) ; } return res ; } function max_PerfectNumbers ( arr , N , K ) { for ( let i = 0 ; i < N ; i ++ ) { arr [ i ] = isPerfect ( arr [ i ] ) == 1 ? 1 : 0 ; } return maxSum ( arr , N , K ) ; } let arr = [ 28 , 2 , 3 , 6 , 496 , 99 , 8128 , 24 ] ; let K = 4 ; let N = arr . length ; document . write ( max_PerfectNumbers ( arr , N , K ) ) ;