【问题标题】:Find maximum product of element each from three Arrays从三个数组中找到每个元素的最大乘积
【发布时间】:2019-10-24 21:59:53
【问题描述】:

给定 3 个具有整数(正数和负数)的可变长度数组,找到可以通过将每个数组中的元素相乘来形成的最大乘积。

例如。

A = [ 10, -10,15,-12];
B = [10, -12,13,-12];
C = [-11, -10, 9,-12];

对于上述数组:最大乘积 = 2160,使用 15、-12、-12。

我尝试使用暴力方法 O(N^3) 使用三个嵌套的 for 循环来实现它但我正在寻找更优化的方法

int[] A = new int[]{10,-10,15,-12};
int[] B = new int[]{10,-12,13,-12};
int[] C = new int[]{-11,-10,9,-12};

int max = Integer.MIN_VALUE;

int pos[][]=new int[3][2];

for (int i=0; i < A.length ; i++ ){

    for (int j=0; j < B.length ; j++ ){

        for (int k=0; k < C.length ; k++ ){

            int prod = A[i] * B[j] * C[k];

            if( prod > max ){
                max = prod;
                pos[0][0]=i;
                pos[1][0]=j;
                pos[2][0]=k;
                pos[0][1]=A[i];
                pos[1][1]=B[j];
                pos[2][1]=C[k];
            }

        } 
    }   
}
System.out.println("Maximum product = "+max+" using "+pos[0][1]+", "+pos[1][1]+", "+pos[2][1]+".");

到目前为止我的想法:

我曾尝试考虑对数组进行排序,但后来意识到我们需要使用绝对值进行排序。 然后我想到了使用具有最大绝对值的元素。

但无法从这里继续讨论如何选择接下来的两个来优化解决方案。

【问题讨论】:

  • 提示:对于正数,您的方法是什么?
  • 我已经为我使用的蛮力方法添加了代码。请帮我优化一下。
  • 只有正数的方法是从每个数组中找到最大值并返回这些数字的乘积。
  • 你可以在 O(n) 中得到每个数组的最小(只有负数时才有意义)和最大数(只有正数时才有意义),然后检查所有可能的组合。因为有效组合的数量非常有限(恒定),所以算法仍然是 O(n)。

标签: arrays algorithm sorting data-structures


【解决方案1】:

一种选择是对所有三个数组进行排序,每个数组花费 O(nlogn) 时间(这不是嵌套的),然后将每个排序数组中最正和负的元素放入另一个数组中O(nlogn) 时间。

此时您只需检查 6 元素数组,看看三个最正元素的乘积是否大于最正元素和两个最负元素的乘积并返回该结果。

【讨论】:

  • 这是不正确的,因为它不需要所有三个元素都来自三个不同的数组
【解决方案2】:

这与How to get the K smallest Products from pairs from two sorted Arrays? 非常相似,只是这里我们有三个列表,并且对最大产品感兴趣。

  1. 找出每个列表的最小值和最大值:minA, maxA, minB, max B、minC 和 maxC

  2. 最大乘积是:

    minA * minB * minC

    minA * minB * maxC

    minA * maxB * minC

    minA * maxB * maxC

    最大A * minB * minC

    最大A * 最小B * 最大C

    最大A * 最大B * 最小C

    最大A * 最大B * 最大C

【讨论】:

    【解决方案3】:

    最大积的形成方式有四种:

    1. 从三个数组中取最大值
    2. 从第一个数组中取最大值,从第二个和第三个数组中取最小值
    3. 从第二个数组中取最大值,从第一个和第三个数组中取最小值
    4. 从第三个数组中取最大值,从第一个和第二个数组中取最小值

    您可以通过排序或简单地通过顺序扫描数组来找到最小和最大元素。

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 2017-01-08
      • 2020-09-06
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多