Find an index such that difference between product of elements before and after it is minimum | C # implementation of the approach ; Function to return the index i such that the absolute difference between product of elements up to that index and the product of rest of the elements of the array is minimum ; To store the required index ; Prefix product array ; Compute the product array ; Iterate the product array to find the index ; Driver code
using System ; class GFG { static int findIndex ( int [ ] a , int n ) { int res = 0 ; long min_diff = Int64 . MaxValue ; long [ ] prod = new long [ n ] ; prod [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prod [ i ] = prod [ i - 1 ] * a [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { long curr_diff = Math . Abs ( ( prod [ n - 1 ] / prod [ i ] ) - prod [ i ] ) ; if ( curr_diff < min_diff ) { min_diff = curr_diff ; res = i ; } } return res ; } static void Main ( ) { int [ ] arr = { 3 , 2 , 5 , 7 , 2 , 9 } ; int N = arr . Length ; Console . WriteLine ( findIndex ( arr , N ) ) ; } }