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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE int findIndex ( int a [ ] , int n ) { int res ; ll min_diff = INT_MAX ; ll prod [ 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 ++ ) { ll curr_diff = abs ( ( prod [ n - 1 ] / prod [ i ] ) - prod [ i ] ) ; if ( curr_diff < min_diff ) { min_diff = curr_diff ; res = i ; } } return res ; } int main ( ) { int arr [ ] = { 3 , 2 , 5 , 7 , 2 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N ) ; return 0 ; }