Find array sum after incrementing by K adjacent elements of every positive element M times | C ++ program for the above approach ; Function to find the nearest non - zero element in the left direction ; Stores the index of the first element greater than 0 from the right side ; Traverse the array in the range [ 1 , N ] ; Check arr [ i ] is greater than 0 ; Update the value of L ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of L ; Update the value of steps [ i ] ; Function to find the nearest non - zero element in the right direction ; Stores the index of the first element greater than 0 from the left side ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Traverse the array from the right side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Update the value of steps [ i ] ; Function to find the sum of the array after the given operation M times ; Stores the distance of the nearest non zero element . ; Stores sum of the initial array arr [ ] ; Traverse the array from the left side ; Update the value of sum ; Print the total sum of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestLeft ( int arr [ ] , int N , vector < int > & steps ) { int L = - N ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { L = - ( N - i ) ; break ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) { L = i ; } steps [ i ] = i - L ; } } void nearestRight ( int arr [ ] , int N , vector < int > & steps ) { int R = 2 * N ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) { R = N + i ; break ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { R = i ; } steps [ i ] = min ( steps [ i ] , R - i ) ; } } int findSum ( int arr [ ] , int N , int M , int K ) { vector < int > steps ( N ) ; int sum = accumulate ( arr , arr + N , 0 ) ; if ( sum == 0 ) { return 0 ; } nearestLeft ( arr , N , steps ) ; nearestRight ( arr , N , steps ) ; for ( int i = 0 ; i < N ; i ++ ) sum += 2 * K * max ( 0 , M - steps [ i ] ) ; return sum ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 2 ; int K = 1 ; cout << findSum ( arr , N , M , K ) ; return 0 ; }