Find array sum after incrementing by K adjacent elements of every positive element M times | 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
def nearestLeft ( arr , N , steps ) : NEW_LINE INDENT L = - N NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT L = - ( N - i ) NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT L = i NEW_LINE DEDENT steps [ i ] = i - L NEW_LINE DEDENT DEDENT def nearestRight ( arr , N , steps ) : NEW_LINE INDENT R = 2 * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT R = N + i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT R = i NEW_LINE DEDENT steps [ i ] = min ( steps [ i ] , R - i ) NEW_LINE DEDENT DEDENT def findSum ( arr , N , M , K ) : NEW_LINE INDENT steps = [ 0 ] * N NEW_LINE s = sum ( arr ) NEW_LINE if ( s == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT nearestLeft ( arr , N , steps ) NEW_LINE nearestRight ( arr , N , steps ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s += 2 * K * max ( 0 , M - steps [ i ] ) NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 0 , 1 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE M = 2 NEW_LINE K = 1 NEW_LINE print ( findSum ( arr , N , M , K ) ) NEW_LINE DEDENT