Find array sum after incrementing by K adjacent elements of every positive element M times | Java 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
import java . util . * ; class GFG { static void nearestLeft ( int arr [ ] , int N , 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 ; } } static void nearestRight ( int arr [ ] , int N , 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 ] = Math . min ( steps [ i ] , R - i ) ; } } static int accumulate ( int [ ] arr , int start , int end ) { int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) sum += arr [ i ] ; return sum ; } static int findSum ( int arr [ ] , int N , int M , int K ) { int [ ] steps = new int [ N ] ; int sum = accumulate ( arr , 0 , N ) ; if ( sum == 0 ) { return 0 ; } nearestLeft ( arr , N , steps ) ; nearestRight ( arr , N , steps ) ; for ( int i = 0 ; i < N ; i ++ ) sum += 2 * K * Math . max ( 0 , M - steps [ i ] ) ; return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 0 , 1 , 0 , 0 } ; int N = arr . length ; int M = 2 ; int K = 1 ; System . out . print ( findSum ( arr , N , M , K ) ) ; } }