Replace every element in a circular array by sum of next K elements | Function to print the required resultant array ; Reverse the array ; Traverse the range ; Store prefix sum ; Find the prefix sum ; Store the answer ; Calculate the answers ; Count of remaining elements ; Add the sum of all elements y times ; Add the remaining elements ; Update ans [ i ] ; If array is reversed print ans [ ] in reverse ; Given array arr [ ] ; Given K ; Function
function sumOfKElements ( arr , n , k ) { let rev = false ; if ( k < 0 ) { rev = true ; k *= - 1 ; let l = 0 , r = n - 1 ; while ( l < r ) { let tmp = arr [ l ] ; arr [ l ] = arr [ r ] ; arr [ r ] = tmp ; l ++ ; r -- ; } } let dp = new Uint8Array ( n ) ; dp [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { dp [ i ] += dp [ i - 1 ] + arr [ i ] ; } let ans = new Uint8Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( i + k < n ) ans [ i ] = dp [ i + k ] - dp [ i ] ; else { let x = k - ( n - 1 - i ) ; let y = Math . floor ( x / n ) ; let rem = x % n ; ans [ i ] = dp [ n - 1 ] - dp [ i ] + y * dp [ n - 1 ] + ( rem - 1 >= 0 ? dp [ rem - 1 ] : 0 ) ; } } if ( rev ) { for ( let i = n - 1 ; i >= 0 ; i -- ) { document . write ( ans [ i ] + " " ) ; } } else { for ( let i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } } let arr = [ 4 , 2 , - 5 , 11 ] ; let N = arr . length ; let K = 3 ; sumOfKElements ( arr , N , K ) ;