Encuentre un índice tal que la diferencia entre el producto de los elementos antes y después sea mínima

Dado un entero arr[] , la tarea es encontrar un índice tal que la diferencia entre el producto de los elementos hasta ese índice (incluido ese índice) y el producto del resto de los elementos sea mínima. Si hay más de uno de estos índices, devuelva el índice mínimo como respuesta. 

Ejemplos:  

Entrada: arr[] = { 2, 2, 1 } 
Salida:
Para índice 0: abs((2) – (2 * 1)) = 0 
Para índice 1: abs((2 * 2) – (1)) = 3

Entrada: arr[] = { 3, 2, 5, 7, 2, 9 } 
Salida:

Una solución simple es recorrer todos los elementos desde el primero hasta el penúltimo elemento. Para cada elemento, encuentre el producto de los elementos hasta este elemento (incluido este elemento). Luego encuentra el producto de los elementos después de él. Finalmente calcule la diferencia. Si la diferencia es mínima hasta el momento, actualice el resultado.

Mejor enfoque: el problema se puede resolver fácilmente usando una array de productos de prefijo prod[] donde prod[i] almacena el producto de los elementos de arr[0] a arr[i] . Por lo tanto, el producto del resto de los elementos se puede encontrar fácilmente dividiendo el producto total de la array por el producto hasta el índice actual. Ahora, itere la array de productos para encontrar el índice con la diferencia mínima. 

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
 
// 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
int findIndex(int a[], int n)
{
    // To store the required index
    int res;
 
    ll min_diff = INT_MAX;
 
    // Prefix product array
    ll prod[n];
    prod[0] = a[0];
 
    // Compute the product array
    for (int i = 1; i < n; i++)
        prod[i] = prod[i - 1] * a[i];
 
    // Iterate the product array to find the index
    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;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 2, 5, 7, 2, 9 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << findIndex(arr, N);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG{
     
// 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
static int findIndex(int a[], int n)
{
    // To store the required index
    int res = 0;
 
    long min_diff = Long.MAX_VALUE;
 
    // Prefix product array
    long prod[] = new long[n];
    prod[0] = a[0];
 
    // Compute the product array
    for (int i = 1; i < n; i++)
        prod[i] = prod[i - 1] * a[i];
 
    // Iterate the product array to find the index
    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;
}
 
// Driver code
public static void main(String arg[])
{
    int arr[] = { 3, 2, 5, 7, 2, 9 };
    int N = arr.length;
 
    System.out.println(findIndex(arr, N));
}
}
 
// This code is contributed by rutvik_56

Python3

# Python3 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
def findIndex(a, n):
  
    # To store the required index
    res, min_diff = None, float('inf')
 
    # Prefix product array
    prod = [None] * n
    prod[0] = a[0]
 
    # Compute the product array
    for i in range(1, n):
        prod[i] = prod[i - 1] * a[i]
 
    # Iterate the product array to find the index
    for i in range(0, n - 1): 
        curr_diff = abs((prod[n - 1] // prod[i]) - prod[i])
 
        if curr_diff < min_diff: 
            min_diff = curr_diff
            res = i
          
    return res
 
# Driver code
if __name__ == "__main__":
  
    arr = [3, 2, 5, 7, 2, 9] 
    N = len(arr)
 
    print(findIndex(arr, N))
 
# This code is contributed by Rituraj Jain

C#

// C# implementation of the approach
using System;
 
class GFG
{
    // 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 
    static int findIndex(int[] a, int n) 
    { 
        // To store the required index 
        int res = 0; 
       
        long min_diff = Int64.MaxValue; 
       
        // Prefix product array 
        long[] prod = new long[n]; 
        prod[0] = a[0]; 
       
        // Compute the product array 
        for (int i = 1; i < n; i++) 
            prod[i] = prod[i - 1] * a[i]; 
       
        // Iterate the product array to find the index 
        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; 
    } 
   
  // Driver code
  static void Main()
  {
        int[] arr = { 3, 2, 5, 7, 2, 9 }; 
        int N = arr.Length; 
       
        Console.WriteLine(findIndex(arr, N)); 
  }
}
 
// This code is contributed by divyeshrabadiya07

PHP

<?php
// PHP 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
function findIndex($a, $n)
{
    $min_diff = PHP_INT_MAX;
 
    // Prefix product array
    $prod = array();
    $prod[0] = $a[0];
 
    // Compute the product array
    for ($i = 1; $i < $n; $i++)
        $prod[$i] = $prod[$i - 1] * $a[$i];
 
    // Iterate the product array to find the index
    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;
}
 
    // Driver code
    $arr = array( 3, 2, 5, 7, 2, 9 );
    $N = count($arr);
 
    echo findIndex($arr, $N);
     
    // This code is contributed by AnkitRai01
?>

Javascript

<script>
    // Javascript 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
    function findIndex(a, n)
    {
        // To store the required index
        let res = 0;
        
        let min_diff = Number.MAX_VALUE;
        
        // Prefix product array
        let prod = new Array(n);
        prod[0] = a[0];
        
        // Compute the product array
        for (let i = 1; i < n; i++)
            prod[i] = prod[i - 1] * a[i];
        
        // Iterate the product array to find the index
        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));
         
        // This code is contributed by suresh07.
</script>
Producción: 

2

 

Complejidad de tiempo: O(n)

Espacio Auxiliar: O(n)

Enfoque sin desbordamiento 
La solución anterior podría causar desbordamiento. Para evitar problemas de desbordamiento, tome un registro de todos los valores de la array. Ahora, la pregunta se reduce a dividir la array en dos mitades con una diferencia absoluta de suma mínima posible. Ahora, la array contiene valores de registro de elementos en cada índice. Mantenga una array de suma de prefijos B que contenga la suma de todos los valores hasta el índice i. Verifique todos los índices, abs(B[n-1] – 2*B[i]) y encuentre el índice con el mínimo valor absoluto posible. 

C++

#include <bits/stdc++.h>
#define ll long long int
using namespace std;
 
// Function to find index
void solve(int Array[], int N)
{
    // Array to store log values of elements
    double Arraynew[N];
    for (int i = 0; i < N; i++) {
        Arraynew[i] = log(Array[i]);
    }
 
    // Prefix Array to Maintain Sum of log values till index i
    double prefixsum[N];
    prefixsum[0] = Arraynew[0];
 
    for (int i = 1; i < N; i++) {
        prefixsum[i] = prefixsum[i - 1] + Arraynew[i];
    }
 
    // Answer Index
    int answer = 0;
    double minabs = abs(prefixsum[N - 1] - 2 * prefixsum[0]);
 
    for (int i = 1; i < N - 1; i++) {
        double ans1 = abs(prefixsum[N - 1] - 2 * prefixsum[i]);
 
        // Find minimum absolute value
        if (ans1 < minabs) {
            minabs = ans1;
            answer = i;
        }
    }
 
    cout << "Index is: " << answer << endl;
}
 
// Driver Code
int main()
{
    int Array[5] = { 1, 4, 12, 2, 6 };
    int N = 5;
    solve(Array, N);
}

Java

public class Main
{
    // Function to find index
    public static void solve(int Array[], int N)
    {
        // Array to store log values of elements
        double Arraynew[] = new double[N];
        for (int i = 0; i < N; i++) {
            Arraynew[i] = Math.log(Array[i]);
        }
      
        // Prefix Array to Maintain Sum of log values till index i
        double prefixsum[] = new double[N];
        prefixsum[0] = Arraynew[0];
      
        for (int i = 1; i < N; i++)
        {
            prefixsum[i] = prefixsum[i - 1] + Arraynew[i];
        }
      
        // Answer Index
        int answer = 0;
        double minabs = Math.abs(prefixsum[N - 1] - 2 *
                                 prefixsum[0]);
      
        for (int i = 1; i < N - 1; i++)
        {
            double ans1 = Math.abs(prefixsum[N - 1] - 2 *
                                   prefixsum[i]);
      
            // Find minimum absolute value
            if (ans1 < minabs)
            {
                minabs = ans1;
                answer = i;
            }
        }
      
        System.out.println("Index is: " + answer);
    }
   
   
 // Driver code
    public static void main(String[] args)
    {
        int Array[] = { 1, 4, 12, 2, 6 };
        int N = 5;
        solve(Array, N);
    }
}
 
// This code is contributed by divyesh072019

Python3

import math
 
# Function to find index
def solve( Array,  N):
 
    # Array to store log values of elements
    Arraynew = [0]*N
    for i in range( N ) :
        Arraynew[i] = math.log(Array[i])
     
  
    # Prefix Array to Maintain Sum of log values till index i
    prefixsum = [0]*N
    prefixsum[0] = Arraynew[0]
  
    for i in range( 1,  N) :
        prefixsum[i] = prefixsum[i - 1] + Arraynew[i]
     
  
    # Answer Index
    answer = 0
    minabs = abs(prefixsum[N - 1] - 2 * prefixsum[0])
  
    for i in range(1, N - 1):
        ans1 = abs(prefixsum[N - 1] - 2 * prefixsum[i])
  
        # Find minimum absolute value
        if (ans1 < minabs):
            minabs = ans1
            answer = i
  
    print("Index is: " ,answer)
  
# Driver Code
if __name__ == "__main__":
    Array = [ 1, 4, 12, 2, 6 ]
    N = 5
    solve(Array, N)
 
# This code is contributed by chitranayal

C#

using System;
using System.Collections;
 
class GFG{
 
// Function to find index
public static void solve(int []Array, int N)
{
     
    // Array to store log values of elements
    double []Arraynew = new double[N];
    for(int i = 0; i < N; i++)
    {
        Arraynew[i] = Math.Log(Array[i]);
    }
   
    // Prefix Array to Maintain Sum of
    // log values till index i
    double []prefixsum = new double[N];
    prefixsum[0] = Arraynew[0];
   
    for(int i = 1; i < N; i++)
    {
        prefixsum[i] = prefixsum[i - 1] +
                        Arraynew[i];
    }
   
    // Answer Index
    int answer = 0;
    double minabs = Math.Abs(prefixsum[N - 1] - 2 *
                             prefixsum[0]);
   
    for(int i = 1; i < N - 1; i++)
    {
        double ans1 = Math.Abs(prefixsum[N - 1] - 2 *
                               prefixsum[i]);
   
        // Find minimum absolute value
        if (ans1 < minabs)
        {
            minabs = ans1;
            answer = i;
        }
    }
   
    Console.WriteLine("Index is: " + answer);
}
 
// Driver code
public static void Main(string []args)
{
    int []Array = { 1, 4, 12, 2, 6 };
    int N = 5;
     
    solve(Array, N);
}
}
 
// This code is contributed by pratham76

Javascript

<script>
 
    // Function to find index
    function solve(array, N)
    {
 
        // Array to store log values of elements
        let Arraynew = new Array(N);
        for(let i = 0; i < N; i++)
        {
            Arraynew[i] = Math.log(array[i]);
        }
 
        // Prefix Array to Maintain Sum of
        // log values till index i
        let prefixsum = new Array(N);
        prefixsum[0] = Arraynew[0];
 
        for(let i = 1; i < N; i++)
        {
            prefixsum[i] = prefixsum[i - 1] +
                            Arraynew[i];
        }
 
        // Answer Index
        let answer = 0;
        let minabs = Math.abs(prefixsum[N - 1] - 2 *
                                 prefixsum[0]);
 
        for(let i = 1; i < N - 1; i++)
        {
            let ans1 = Math.abs(prefixsum[N - 1] - 2 *
                                   prefixsum[i]);
 
            // Find minimum absolute value
            if (ans1 < minabs)
            {
                minabs = ans1;
                answer = i;
            }
        }
 
        document.write("Index is: " + answer + "</br>");
    }
     
    let array = [ 1, 4, 12, 2, 6 ];
    let N = 5;
      
    solve(array, N);
     
</script>
Producción: 

Index is: 2

 

Publicación traducida automáticamente

Artículo escrito por rupesh_rao y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *