Replace every element in a circular array by sum of next K elements | C ++ program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Given K ; Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfKElements ( int arr [ ] , int n , int k ) { bool rev = false ; if ( k < 0 ) { rev = true ; k *= -1 ; int l = 0 , r = n - 1 ; while ( l < r ) { int tmp = arr [ l ] ; arr [ l ] = arr [ r ] ; arr [ r ] = tmp ; l ++ ; r -- ; } } int dp [ n ] = { 0 } ; dp [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] += dp [ i - 1 ] + arr [ i ] ; } int ans [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + k < n ) ans [ i ] = dp [ i + k ] - dp [ i ] ; else { int x = k - ( n - 1 - i ) ; int y = x / n ; int rem = x % n ; ans [ i ] = dp [ n - 1 ] - dp [ i ] + y * dp [ n - 1 ] + ( rem - 1 >= 0 ? dp [ rem - 1 ] : 0 ) ; } } if ( rev ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { cout << ans [ i ] << " ▁ " ; } } else { for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 4 , 2 , -5 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; sumOfKElements ( arr , N , K ) ; }