给定一个由不同长度的数组组成的列表arr [] ,任务是找到可以通过从列表中存在的每个数组中恰好取一个元素来找到可形成的最大乘积。
例子:
Input: arr[] = {{-3, -4}, {1, 2, -3}}
Output: 12
Explanation:
Pick -4 from the first array and -3 from the second array.
Therefore, maximum possible product is 12.
Input: arr[] = {{1, -1}, {2, 3}, {10, -100, 20}}
Output: 300
Explanation:
Pick -1 from the first array and 3 from the second array and -100 from the third array.
Therefore, maximum product is 300.
天真的方法:解决此问题的最简单方法是使用递归从列表的每个数组中选取一个元素,然后从所有可能的组合中选择最大乘积,以找到元素的每种可能组合。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Stores the maximum product
int maximum = -INT_MAX;
// Function to find maximum product
// possible by taking exactly one element
// from each array of the list
void calculateProduct(vector > &List,
int index, int product)
{
// If last index is encountered
if(index + 1 == List.size())
{
for (int i :List[index])
{
// Find the maximum product
maximum = max(maximum, product *i);
}
// Otherwise, recursively calculate
// maximum product for every element
}
else
{
for(int i: List[index])
calculateProduct(List, index + 1, product * i);
}
}
// Driver Code
// Count of given arrays
int main()
{
int N = 2;
// Given list of N arrays
vector > arr = {{-3, -4}, {1, 2, -3}};
// Calculates the maximum
// possible product
calculateProduct(arr, 0, 1);
// Print the maximum product
cout << maximum;
return 0;
}
// This code is contributed by mohit kumar 29
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
static int maximum = -Integer.MAX_VALUE;
// Function to find maximum product
// possible by taking exactly one element
// from each array of the list
static void calculateProduct(int[][] List,
int index,
int product)
{
// If last index is encountered
if (index + 1 == List.length)
{
for(int i:List[index])
{
// Find the maximum product
maximum = Math.max(maximum, product * i);
}
// Otherwise, recursively calculate
// maximum product for every element
}
else
{
for(int i:List[index])
calculateProduct(List, index + 1,
product * i);
}
}
// Driver Code
public static void main(String[] args)
{
int N = 2;
// Given list of N arrays
int[][] arr = { { -3, -4 }, { 1, 2, -3 } };
// Calculates the maximum
// possible product
calculateProduct(arr, 0, 1);
// Print the maximum product
System.out.print(maximum);
}
}
// This code is contributed by code_hunt
Python3
# Python program for the above approach
# Stores the maximum product
maximum = -float('INF')
# Function to find maximum product
# possible by taking exactly one element
# from each array of the list
def calculateProduct(List, index, product):
# If last index is encountered
if(index + 1 == len(List)):
for i in List[index]:
global maximum
# Find the maximum product
maximum = max(maximum, product * i)
# Otherwise, recursively calculate
# maximum product for every element
else:
for i in List[index]:
calculateProduct(List, index + 1, product * i)
# Driver Code
# Count of given arrays
N = 2
# Given list of N arrays
arr = [[-3, -4], [1, 2, -3]]
# Calculates the maximum
# possible product
calculateProduct(arr, 0, 1)
# Print the maximum product
print(maximum)
C#
// C# program for the
// above approach
using System;
public class GFG{
static int maximum = -int.MaxValue;
// Function to find maximum product
// possible by taking exactly one element
// from each array of the list
static void calculateProduct(int[,] list,
int index,
int product)
{
// If last index is encountered
if (index + 1 == list.GetLength(0))
{
foreach(int i in GetRow(list,index))
{
// Find the maximum product
maximum = Math.Max(maximum, product * i);
}
// Otherwise, recursively calculate
// maximum product for every element
}
else
{
foreach(int i in GetRow(list,index))
calculateProduct(list, index + 1,
product * i);
}
}
public static int[] GetRow(int[,] matrix, int row)
{
var rowLength = matrix.GetLength(1);
var rowVector = new int[rowLength];
for (var i = 0; i < rowLength; i++)
{
rowVector[i] = matrix[row, i];
}
return rowVector;
}
// Driver Code
public static void Main(String[] args)
{
// Given list of N arrays
int[,] arr = { { -3, -4,0 }, { 1, 2, -3 } };
// Calculates the maximum
// possible product
calculateProduct(arr, 0, 1);
// Print the maximum product
Console.Write(maximum);
}
}
// This code is contributed by 29AjayKumar
C++14
// CPP program for the above approach
#include
using namespace std;
// Function to return the product of 2 numbers
int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == INT_MIN or number_2 == INT_MIN)
return 0;
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
pair calculateProduct(vector> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = *max_element(List[index].begin(),List[index].end());
int lowest = *min_element(List[index].begin(),List[index].end());
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.size()){
if(lowest < 0 and highest >= 0)
return {highest, lowest};
else if(lowest <= 0 and highest <= 0)
return {INT_MIN, lowest};
else if(lowest >= 0 and highest >= 0)
return {highest, INT_MIN};
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
pair temp = calculateProduct(List, index + 1);
int positive = temp.first;
int negative = temp.second;
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 and highest >= 0)
return {max(highPos, lowNeg), min(highNeg, lowPos)};
else if(lowest <= 0 and highest <= 0)
return {lowNeg, lowPos};
else if(lowest >= 0 and highest >= 0)
return {max(lowPos, highPos), min(lowNeg, highNeg)};
}
// Driver Code
int main()
{
// Count of given arrays
int N = 2;
// Given list of N arrays
vector>arr{{-3, -4}, {1, 2, -3}};
// Store the maximum positive and
// minimum negative product possible
pair ans = calculateProduct(arr, 0);
// Print the maximum product
cout<
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to return the product of 2 numbers
static int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == Integer.MIN_VALUE || number_2 == Integer.MIN_VALUE)
{
return 0;
}
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
static ArrayList calculateProduct(ArrayList> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = Collections.max(List.get(index));
int lowest = Collections.min(List.get(index));
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.size())
{
if(lowest < 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(highest, lowest)));
}
else if(lowest <= 0 && highest <= 0)
{
return (new ArrayList(Arrays.asList(Integer.MIN_VALUE, lowest)));
}
else if(lowest >= 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(highest,Integer.MIN_VALUE)));
}
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
ArrayList temp = calculateProduct(List, index + 1);
int positive = temp.get(0);
int negative = temp.get(1);
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(Math.max(highPos, lowNeg), Math.min(highNeg, lowPos))));
}
else if(lowest <= 0 && highest <= 0)
{
return (new ArrayList(Arrays.asList(lowNeg, lowPos)));
}
else if(lowest >= 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(Math.max(lowPos, highPos), Math.min(lowNeg, highNeg))));
}
return (new ArrayList(Arrays.asList(0,0)));
}
// Driver Code
public static void main (String[] args) {
// Count of given arrays
int N = 2;
// Given list of N arrays
ArrayList> arr = new ArrayList>();
arr.add(new ArrayList(Arrays.asList(-3, -4)));
arr.add(new ArrayList(Arrays.asList(1, 2, -3)));
// Store the maximum positive and
// minimum negative product possible
ArrayList ans = calculateProduct(arr, 0);
// Print the maximum product
System.out.println(ans.get(0));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python program for the above approach
# Function to return the product of 2 numbers
def findProduct(number_1, number_2):
# If any of the two numbers is None
if(number_1 == None or number_2 == None):
return 0
# Otherwise, return the product
else:
return number_1 * number_2
# Function to calculate maximum product
# by taking only one element from each
# array present in the list
def calculateProduct(List, index):
# Find the maximum and minimum
# present in the current array
highest = max(List[index])
lowest = min(List[index])
# If last index is reached, then
# return the highest(positive)
# and lowest(negative) values
if(index + 1 == len(List)):
if(lowest < 0 and highest >= 0):
return [highest, lowest]
elif(lowest <= 0 and highest <= 0):
return [None, lowest]
elif(lowest >= 0 and highest >= 0):
return [highest, None]
# Store the positive and negative products
# returned by calculating for the
# remaining arrays
[positive, negative] = calculateProduct(List, index + 1)
# Calculate for all combinations of
# highest, lowest with positive, negative
# Store highest positive product
highPos = findProduct(highest, positive)
# Store product of highest with negative
highNeg = findProduct(highest, negative)
# Store product of lowest with positive
lowPos = findProduct(lowest, positive)
# Store lowest negative product
lowNeg = findProduct(lowest, negative)
# Return the maximum positive and
# minimum negative product
if(lowest < 0 and highest >= 0):
return [max(highPos, lowNeg), min(highNeg, lowPos)]
elif(lowest <= 0 and highest <= 0):
return [lowNeg, lowPos]
elif(lowest >= 0 and highest >= 0):
return [max(lowPos, highPos), min(lowNeg, highNeg)]
# Driver Code
# Count of given arrays
N = 2
# Given list of N arrays
arr = [[-3, -4], [1, 2, -3]]
# Store the maximum positive and
# minimum negative product possible
positive, negative = calculateProduct(arr, 0)
# Print the maximum product
print(positive)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
// Function to return the product of 2 numbers
static int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == Int32.MinValue || number_2 == Int32.MinValue)
{
return 0;
}
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
static List calculateProduct(List> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = List[index].Max();
int lowest = List[index].Min();
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.Count)
{
if(lowest < 0 && highest >= 0)
{
return (new List(){highest,lowest});
}
else if(lowest <= 0 && highest <= 0)
{
return (new List(){Int32.MinValue, lowest});
}
else if(lowest >= 0 && highest >= 0)
{
return (new List(){highest, Int32.MinValue});
}
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
List temp = calculateProduct(List, index + 1);
int positive = temp[0];
int negative = temp[1];
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 && highest >= 0)
{
return (new List(){Math.Max(highPos, lowNeg), Math.Min(highNeg, lowPos)});
}
else if(lowest <= 0 && highest <= 0)
{
return (new List(){lowNeg, lowPos});
}
else if(lowest >= 0 && highest >= 0)
{
return (new List(){Math.Max(lowPos, highPos), Math.Min(lowNeg, highNeg)});
}
return (new List(){0,0});
}
// Driver Code
static public void Main ()
{
// Given list of N arrays
List> arr = new List>();
arr.Add(new List(){-3, -4});
arr.Add(new List(){1, 2, -3});
// Store the maximum positive and
// minimum negative product possible
List ans = calculateProduct(arr, 0);
// Print the maximum product
Console.WriteLine(ans[0]);
}
}
// This code is contributed by rag2127.
12
时间复杂度: O(2 N )
辅助空间: O(1)
高效方法:为了优化上述方法,其思想是考虑每个阵列中最低的负数(如果有)和最高的正数(如果有)以使乘积最大化。请按照以下步骤解决问题:
- 遍历数组arr []的列表。
- 对于列表中的每个数组,说arr [index] ,找到其中存在的最大和最小元素。
- 如果已到达最后一个索引,则以对的形式返回最大值和最小值。
- 如果获得的最大值为负,则将其设置为None 。如果获得的最小值为正,则将其设置为“无”
- 除此以外:
- 递归调用(index + 1) ,即calculateProduct(list,index + 1)并将结果存储在[positive,negative]中。
- 找到在步骤1中获得的最大,最小值与在步骤3.1中发现的正,负的所有组合。
- 返回所有组合之间形成的最大正数和最小负数。
- 完成上述步骤后,打印形成的最大产品。
下面是上述方法的实现:
C++ 14
// CPP program for the above approach
#include
using namespace std;
// Function to return the product of 2 numbers
int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == INT_MIN or number_2 == INT_MIN)
return 0;
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
pair calculateProduct(vector> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = *max_element(List[index].begin(),List[index].end());
int lowest = *min_element(List[index].begin(),List[index].end());
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.size()){
if(lowest < 0 and highest >= 0)
return {highest, lowest};
else if(lowest <= 0 and highest <= 0)
return {INT_MIN, lowest};
else if(lowest >= 0 and highest >= 0)
return {highest, INT_MIN};
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
pair temp = calculateProduct(List, index + 1);
int positive = temp.first;
int negative = temp.second;
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 and highest >= 0)
return {max(highPos, lowNeg), min(highNeg, lowPos)};
else if(lowest <= 0 and highest <= 0)
return {lowNeg, lowPos};
else if(lowest >= 0 and highest >= 0)
return {max(lowPos, highPos), min(lowNeg, highNeg)};
}
// Driver Code
int main()
{
// Count of given arrays
int N = 2;
// Given list of N arrays
vector>arr{{-3, -4}, {1, 2, -3}};
// Store the maximum positive and
// minimum negative product possible
pair ans = calculateProduct(arr, 0);
// Print the maximum product
cout<
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to return the product of 2 numbers
static int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == Integer.MIN_VALUE || number_2 == Integer.MIN_VALUE)
{
return 0;
}
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
static ArrayList calculateProduct(ArrayList> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = Collections.max(List.get(index));
int lowest = Collections.min(List.get(index));
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.size())
{
if(lowest < 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(highest, lowest)));
}
else if(lowest <= 0 && highest <= 0)
{
return (new ArrayList(Arrays.asList(Integer.MIN_VALUE, lowest)));
}
else if(lowest >= 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(highest,Integer.MIN_VALUE)));
}
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
ArrayList temp = calculateProduct(List, index + 1);
int positive = temp.get(0);
int negative = temp.get(1);
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(Math.max(highPos, lowNeg), Math.min(highNeg, lowPos))));
}
else if(lowest <= 0 && highest <= 0)
{
return (new ArrayList(Arrays.asList(lowNeg, lowPos)));
}
else if(lowest >= 0 && highest >= 0)
{
return (new ArrayList(Arrays.asList(Math.max(lowPos, highPos), Math.min(lowNeg, highNeg))));
}
return (new ArrayList(Arrays.asList(0,0)));
}
// Driver Code
public static void main (String[] args) {
// Count of given arrays
int N = 2;
// Given list of N arrays
ArrayList> arr = new ArrayList>();
arr.add(new ArrayList(Arrays.asList(-3, -4)));
arr.add(new ArrayList(Arrays.asList(1, 2, -3)));
// Store the maximum positive and
// minimum negative product possible
ArrayList ans = calculateProduct(arr, 0);
// Print the maximum product
System.out.println(ans.get(0));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python program for the above approach
# Function to return the product of 2 numbers
def findProduct(number_1, number_2):
# If any of the two numbers is None
if(number_1 == None or number_2 == None):
return 0
# Otherwise, return the product
else:
return number_1 * number_2
# Function to calculate maximum product
# by taking only one element from each
# array present in the list
def calculateProduct(List, index):
# Find the maximum and minimum
# present in the current array
highest = max(List[index])
lowest = min(List[index])
# If last index is reached, then
# return the highest(positive)
# and lowest(negative) values
if(index + 1 == len(List)):
if(lowest < 0 and highest >= 0):
return [highest, lowest]
elif(lowest <= 0 and highest <= 0):
return [None, lowest]
elif(lowest >= 0 and highest >= 0):
return [highest, None]
# Store the positive and negative products
# returned by calculating for the
# remaining arrays
[positive, negative] = calculateProduct(List, index + 1)
# Calculate for all combinations of
# highest, lowest with positive, negative
# Store highest positive product
highPos = findProduct(highest, positive)
# Store product of highest with negative
highNeg = findProduct(highest, negative)
# Store product of lowest with positive
lowPos = findProduct(lowest, positive)
# Store lowest negative product
lowNeg = findProduct(lowest, negative)
# Return the maximum positive and
# minimum negative product
if(lowest < 0 and highest >= 0):
return [max(highPos, lowNeg), min(highNeg, lowPos)]
elif(lowest <= 0 and highest <= 0):
return [lowNeg, lowPos]
elif(lowest >= 0 and highest >= 0):
return [max(lowPos, highPos), min(lowNeg, highNeg)]
# Driver Code
# Count of given arrays
N = 2
# Given list of N arrays
arr = [[-3, -4], [1, 2, -3]]
# Store the maximum positive and
# minimum negative product possible
positive, negative = calculateProduct(arr, 0)
# Print the maximum product
print(positive)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
// Function to return the product of 2 numbers
static int findProduct(int number_1, int number_2)
{
// If any of the two numbers is None
if(number_1 == Int32.MinValue || number_2 == Int32.MinValue)
{
return 0;
}
// Otherwise, return the product
else
return number_1 * number_2;
}
// Function to calculate maximum product
// by taking only one element from each
// array present in the list
static List calculateProduct(List> List, int index)
{
// Find the maximum and minimum
// present in the current array
int highest = List[index].Max();
int lowest = List[index].Min();
// If last index is reached, then
// return the highest(positive)
// and lowest(negative) values
if(index + 1 == List.Count)
{
if(lowest < 0 && highest >= 0)
{
return (new List(){highest,lowest});
}
else if(lowest <= 0 && highest <= 0)
{
return (new List(){Int32.MinValue, lowest});
}
else if(lowest >= 0 && highest >= 0)
{
return (new List(){highest, Int32.MinValue});
}
}
// Store the positive and negative products
// returned by calculating for the
// remaining arrays
List temp = calculateProduct(List, index + 1);
int positive = temp[0];
int negative = temp[1];
// Calculate for all combinations of
// highest, lowest with positive, negative
// Store highest positive product
int highPos = findProduct(highest, positive);
// Store product of highest with negative
int highNeg = findProduct(highest, negative);
// Store product of lowest with positive
int lowPos = findProduct(lowest, positive);
// Store lowest negative product
int lowNeg = findProduct(lowest, negative);
// Return the maximum positive and
// minimum negative product
if(lowest < 0 && highest >= 0)
{
return (new List(){Math.Max(highPos, lowNeg), Math.Min(highNeg, lowPos)});
}
else if(lowest <= 0 && highest <= 0)
{
return (new List(){lowNeg, lowPos});
}
else if(lowest >= 0 && highest >= 0)
{
return (new List(){Math.Max(lowPos, highPos), Math.Min(lowNeg, highNeg)});
}
return (new List(){0,0});
}
// Driver Code
static public void Main ()
{
// Given list of N arrays
List> arr = new List>();
arr.Add(new List(){-3, -4});
arr.Add(new List(){1, 2, -3});
// Store the maximum positive and
// minimum negative product possible
List ans = calculateProduct(arr, 0);
// Print the maximum product
Console.WriteLine(ans[0]);
}
}
// This code is contributed by rag2127.
12
时间复杂度: O(N * length(array))
辅助空间: O(1)