Find an index such that difference between product of elements before and after it is minimum | 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
function findIndex ( a , n ) { let res = 0 ; let min_diff = Number . MAX_VALUE ; let prod = new Array ( n ) ; prod [ 0 ] = a [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) prod [ i ] = prod [ i - 1 ] * a [ i ] ; for ( let i = 0 ; i < n - 1 ; i ++ ) { let curr_diff = Math . abs ( parseInt ( prod [ n - 1 ] / prod [ i ] , 10 ) - prod [ i ] ) ; if ( curr_diff < min_diff ) { min_diff = curr_diff ; res = i ; } } return res ; } let arr = [ 3 , 2 , 5 , 7 , 2 , 9 ] ; let N = arr . length ; document . write ( findIndex ( arr , N ) ) ;