📌  相关文章
📜  找到一个索引,以使前后元素乘积之间的差异最小

📅  最后修改于: 2021-04-29 18:46:35             🧑  作者: Mango

给定一个整数arr [] ,任务是找到一个索引,使得直到该索引(包括该索引)的元素乘积与其余元素的乘积之差最小。如果存在多个这样的索引,则返回最小索引作为答案。

例子:

一个简单的解决方案是遍历所有元素,从第一个元素倒数第二个元素。对于每个元素,找到元素的乘积,直到该元素(包括该元素)为止。然后在其后找到元素的乘积。最后计算差异。如果到目前为止的差异很小,请更新结果。

更好的方法:使用前缀乘积数组prod []可以轻松解决该问题,其中prod [i]存储从arr [0]arr [i]的元素乘积。因此,通过将阵列的总乘积除以乘积直至当前索引,可以轻松找到其余元素的乘积。现在,迭代乘积数组以找到差异最小的索引。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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


Javascript


C++
#include 
#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


输出:
2

无溢出的方法
上述解决方案可能会导致溢出。为防止溢出问题,请记录阵列的所有值。现在,问题归结为将数组分为两半,总和的绝对差最小。现在,数组包含每个索引处元素的日志值。维护一个前缀和数组B,该数组保存所有值的和直到索引i。检查所有索引abs(B [n-1] – 2 * B [i])并找到具有最小可能绝对值的索引。

C++

#include 
#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

Java脚本


输出:
Index is: 2