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' 的整型變數來儲存子集乘積的和。接下來,使用一個 for 迴圈,該迴圈將執行到陣列的長度。
步驟 4 − 我們將宣告並初始化另一個名為 'prod' 的整型變數來儲存每次迭代期間子集的乘積。
步驟 5 − 現在,在第一個迴圈內部定義另一個 for 迴圈,該迴圈將從 '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()',它檢查兩個指定值的最小值。記住關於靜態方法的一件事是,它們可以在不建立任何物件的情況下被呼叫,我們只需使用類名和點運算子 (.)。