Maximum sum of K | Javascript program for the above approach ; Function to print the sum of subarray of length K having maximum distinct prime factors ; If K exceeds N ; Stores the count of distinct primes ; True , if index ' i ' is a prime ; Initialize the count of factors to 0 and set all indices as prime ; If i is prime ; Number is prime ; Count of factors of a prime number is 1 ; Increment CountDistinct as the factors of i ; Mark its multiple non - prime ; Compute sum of first K - length subarray ; Compute sums of remaining windows by removing first element of the previous window and adding last element of the current window ; Print the maximum sum ; Given array ; Given size of subarray ; Size of the array
let MAX = 100001 function maxSum ( arr , N , K ) { if ( N < K ) { document . write ( " " ) ; return - 1 ; } let CountDistinct = new Array ( MAX + 1 ) ; let prime = new Array ( MAX + 1 ) ; for ( let i = 0 ; i <= MAX ; i ++ ) { CountDistinct [ i ] = 0 ; prime [ i ] = true ; } for ( let i = 2 ; i <= MAX ; i ++ ) { if ( prime [ i ] == true ) { CountDistinct [ i ] = 1 ; for ( let j = i * 2 ; j <= MAX ; j += i ) { CountDistinct [ j ] ++ ; prime [ j ] = false ; } } } let Maxarr_sum = 0 , DistPrimeSum = 0 ; for ( let i = 0 ; i < K ; i ++ ) { Maxarr_sum += arr [ i ] ; DistPrimeSum += CountDistinct [ arr [ i ] ] ; } let curr_sum = DistPrimeSum ; let curr_arrSum = Maxarr_sum ; for ( let i = K ; i < N ; i ++ ) { curr_sum += CountDistinct [ arr [ i ] ] - CountDistinct [ arr [ i - K ] ] ; curr_arrSum += arr [ i ] - arr [ i - K ] ; if ( curr_sum > DistPrimeSum ) { DistPrimeSum = curr_sum ; Maxarr_sum = curr_arrSum ; } else if ( curr_sum == DistPrimeSum ) { Maxarr_sum = Math . max ( curr_arrSum , Maxarr_sum ) ; } } document . write ( Maxarr_sum ) ; } let arr = [ 1 , 4 , 2 , 10 , 3 ] ; let K = 3 ; let N = arr . length maxSum ( arr , N , K ) ;