Finding the maximum subarray product.
Here’s an example of a Java program that finds the maximum subarray product in an array:
public class MaximumSubarrayProduct { public static long findMaxSubarrayProduct(int[] nums) { if (nums == null || nums.length == 0) { throw new IllegalArgumentException("Input array is empty or null."); } long maxProduct = nums[0]; long maxEndingHere = nums[0]; long minEndingHere = nums[0]; for (int i = 1; i < nums.length; i++) { // Calculate the maximum and minimum product ending at the current element long tempMax = maxEndingHere * nums[i]; long tempMin = minEndingHere * nums[i]; // Update the maximum and minimum product ending at the current element maxEndingHere = Math.max(nums[i], Math.max(tempMax, tempMin)); minEndingHere = Math.min(nums[i], Math.min(tempMax, tempMin)); // Update the maximum product so far maxProduct = Math.max(maxProduct, maxEndingHere); } return maxProduct; } public static void main(String[] args) { int[] nums = {2, 3, -2, 4, -1}; long maxProduct = findMaxSubarrayProduct(nums); System.out.println("Maximum subarray product: " + maxProduct); } }
In this program, the `findMaxSubarrayProduct` method takes an array of integers as input and returns the maximum subarray product. It uses the concept of dynamic programming to keep track of the maximum and minimum product ending at each element. The maximum product is updated by taking the maximum of the current element, the maximum product ending at the previous element times the current element, and the minimum product ending at the previous element times the current element.
The program demonstrates the usage of the `findMaxSubarrayProduct` method by finding the maximum subarray product of the array `[2, 3, -2, 4, -1]`. The result is then printed to the console.
When you run the program, it will output:
Maximum subarray product: 48
This indicates that the maximum subarray product of the given array is 48.