Java 用于寻找数组的最小乘积子集
数组是一种线性数据结构,用于存储具有相似数据类型的一组元素。它以顺序方式存储数据。一旦创建了一个数组,就无法改变其大小,即它具有固定长度。
问题陈述指出,对于给定的数组,我们必须找到其子集的最小乘积。在本文中,我们将尝试找到给定问题的解决方案。
最小乘积子集的程序
示例1
让我们通过一个示例来理解问题和可能的解决方案。
对于上面的数组,可能的一些子集可以是−
5 | 5, 6 | 5, 6, 7 | 5, 6, 7, 8 | 5, 6, 7, 8, 9 | 6 | 6, 7, 8 | 9, 10, 11 | 8, 9 等等。
现在,我们将计算它们的乘积并返回其中的最小值。这里,最小值是5。
数组的语法
Data_Type[] nameOfarray; // declaration
Or,
Data_Type nameOfarray[]; // declaration
Or,
// declaration with size
Data_Type nameOfarray[] = new Data_Type[ sizeofarray ];
// declaration and initialization
Data_Type nameOfarray[] = { values separated with comma };
我们可以在程序中使用上述任何一种语法。
步骤
- 步骤1 - 我们首先导入’java.lang.Math’包,以便可以使用类’Math’的方法’min()’来检查两个给定参数中的最小值。
-
步骤2 - 现在,创建一个名为’Subset’的类,并在其中定义一个名为’minProduct()’的方法,带有一个数组作为参数。
-
步骤3 - 在’minProduct()’方法内部,声明并初始化一个整数变量’res’,用于存储子集的乘积之和。进一步进行,使用一个循环,该循环将运行到数组的长度。
-
步骤4 - 我们将声明并初始化另一个整数变量’prod’,用于在每次迭代中存储子集的乘积。
-
步骤5 - 现在,在第一个循环内定义另一个循环,该循环将从’i + 1’运行到数组的长度。在每次迭代中,它将检查乘积之和和子集乘积之间的最小值。
-
步骤6 - 最后,在main()方法中,我们将声明并初始化两个整数类型的数组,以找到它们的最小子集乘积。接下来创建一个名为’obj’的’Subset’类的对象,并使用这个对象调用带有参数的’minProduct()’方法。
示例
import java.lang.Math;
class Subset {
// method that will calculate the minimum product
void minProduct(int aray[]) {
int res = aray[0];
// to store sum of product
for (int i = 0; i < aray.length; i++) {
int prod = aray[i];
for (int j = i + 1; j < aray.length; j++) {
res = Math.min(res, prod);
prod = prod * aray[j];
// calculating product
}
res = Math.min(res, prod);
// checking minimum
}
System.out.println("Minimum product of Sub array is: " + res);
}
}
public class Minsub {
public static void main(String[] args) {
int aray1[] = { 4, -6, 3, 6};
int aray2[] = { 3, 5, 9, 7, 12, 30 };
Subset obj = new Subset();
// object creation
// calling the method using object
obj.minProduct(aray1);
obj.minProduct(aray2);
}
}
输出
Minimum product of Sub array is: -432
Minimum product of Sub array is: 3
结论
我们讨论了如何找到给定数组的子集的最小乘积的解决方案。此外,我们还发现了声明和初始化数组的语法。我们使用了一个静态方法’min()’来检查两个指定值的最小值。请记住静态方法的一件事,它们可以在不创建任何对象的情况下调用,我们只需要使用类名和点操作符(.)。