Java Online Compiler
Example: Maximum Product Subarray - Brute Force in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Maximum Product Subarray - Brute Force import java.util.Arrays; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] nums1 = {2, 3, -2, 4}; System.out.println("Array: " + Arrays.toString(nums1) + ", Max Product: " + maxProductBruteForce(nums1)); // Expected: 6 int[] nums2 = {-2, 0, -1}; System.out.println("Array: " + Arrays.toString(nums2) + ", Max Product: " + maxProductBruteForce(nums2)); // Expected: 0 int[] nums3 = {-2, 3, -4}; System.out.println("Array: " + Arrays.toString(nums3) + ", Max Product: " + maxProductBruteForce(nums3)); // Expected: 24 } public static int maxProductBruteForce(int[] nums) { if (nums == null || nums.length == 0) { return 0; // Or throw an exception, depending on requirements } int maxProduct = nums[0]; // Initialize with the first element // Step 1: Iterate through all possible starting points (i) for (int i = 0; i < nums.length; i++) { int currentProduct = 1; // Initialize current product for each new subarray // Step 2: Iterate through all possible ending points (j) from the current start for (int j = i; j < nums.length; j++) { // Step 3: Multiply the current element to the current product currentProduct *= nums[j]; // Step 4: Update maxProduct if currentProduct is greater if (currentProduct > maxProduct) { maxProduct = currentProduct; } } } return maxProduct; } }
Output
Clear
ADVERTISEMENTS