Make all array elements equal by replacing adjacent pairs by their sum | Function to count the minimum number of pairs of adjacent elements required to be replaced by their sum to make all array elements equal ; Stores the prefix sum of the array ; Calculate the prefix sum array ; Stores the maximum number of subarrays into which the array can be split ; Iterate over all possible sums ; Traverse the array ; If the sum is equal to the current prefix sum ; Increment count of groups by 1 ; Otherwise discard this subgroup sum ; Update the maximum this of subarrays ; Return the minimum number of operations ; Driver Code ; Function Call
function minSteps ( a , n ) { var prefix_sum = Array ( n ) . fill ( 0 ) ; prefix_sum [ 0 ] = a [ 0 ] ; for ( var i = 1 ; i < n ; i ++ ) prefix_sum [ i ] += prefix_sum [ i - 1 ] + a [ i ] ; var mx = - 1 ; for ( var subgroupsum = 0 ; subgroupsum < prefix_sum . length ; subgroupsum ++ ) { var sum = 0 ; var i = 0 ; var grp_count = 0 ; while ( i < n ) { sum += a [ i ] ; if ( sum == prefix_sum [ subgroupsum ] ) { grp_count += 1 ; sum = 0 ; } else if ( sum > prefix_sum [ subgroupsum ] ) { grp_count = - 1 ; break ; } i += 1 ; } if ( grp_count > mx ) mx = grp_count ; } return n - mx ; } var A = [ 1 , 2 , 3 , 2 , 1 , 3 ] ; var N = A . length ; document . write ( minSteps ( A , N ) ) ;