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.Scanner; // Included as per template, though not strictly used in this example. // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] nums = {2, 3, -2, 4}; // int[] nums = {-2, 0, -1}; // Another test case: expected 0 // int[] nums = {-2, -3, -1}; // Another test case: expected 6 (from [-2, -3]) if (nums == null || nums.length == 0) { System.out.println("The array is empty. Max product: 0"); return; } // Step 1: Initialize max_product with the first element of the array // This handles cases where all elements are negative or single element arrays. long max_product = nums[0]; // Step 2: Iterate through all possible starting points (i) for (int i = 0; i < nums.length; i++) { long current_product = 1; // Initialize product for current subarray // Step 3: Iterate through all possible ending points (j) from the current start for (int j = i; j < nums.length; j++) { // Step 4: Multiply current_product by the element at index j current_product *= nums[j]; // Step 5: Update max_product if current_product is greater if (current_product > max_product) { max_product = current_product; } } } System.out.println("Maximum product subarray (Brute Force): " + max_product); } }
Output
Clear
ADVERTISEMENTS