Replace every element in a circular array by sum of next K elements | Function to print 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 ; Driver Code ; Given array arr ; Given K ; Function
def sumOfKElements ( arr , n , k ) : NEW_LINE INDENT rev = False ; NEW_LINE if ( k < 0 ) : NEW_LINE INDENT rev = True ; NEW_LINE k *= - 1 ; NEW_LINE l = 0 ; NEW_LINE r = n - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT tmp = arr [ l ] ; NEW_LINE arr [ l ] = arr [ r ] ; NEW_LINE arr [ r ] = tmp ; NEW_LINE l += 1 ; NEW_LINE r -= 1 ; NEW_LINE DEDENT DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] += dp [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT ans = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i + k < n ) : NEW_LINE INDENT ans [ i ] = dp [ i + k ] - dp [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = k - ( n - 1 - i ) ; NEW_LINE y = x // n ; NEW_LINE rem = x % n ; NEW_LINE ans [ i ] = ( dp [ n - 1 ] - dp [ i ] + y * dp [ n - 1 ] + ( dp [ rem - 1 ] if rem - 1 >= 0 else 0 ) ) ; NEW_LINE DEDENT DEDENT if ( rev ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , - 5 , 11 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 3 ; NEW_LINE sumOfKElements ( arr , N , K ) ; NEW_LINE DEDENT