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
< ? php function findIndex ( $ a , $ n ) { $ min_diff = PHP_INT_MAX ; $ prod = array ( ) ; $ prod [ 0 ] = $ a [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) $ prod [ $ i ] = $ prod [ $ i - 1 ] * $ a [ $ i ] ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { $ curr_diff = abs ( ( $ prod [ $ n - 1 ] / $ prod [ $ i ] ) - $ prod [ $ i ] ) ; if ( $ curr_diff < $ min_diff ) { $ min_diff = $ curr_diff ; $ res = $ i ; } } return $ res ; } $ arr = array ( 3 , 2 , 5 , 7 , 2 , 9 ) ; $ N = count ( $ arr ) ; echo findIndex ( $ arr , $ N ) ; ? >