Finding the maximum subarray length with given product.
Here’s an example of a Java program that finds the maximum subarray length with a given product:
import java.util.HashMap; public class MaximumSubarrayLength { public static int findMaxSubarrayLength(int[] nums, int targetProduct) { int maxLength = 0; int product = 1; HashMap<Integer, Integer> map = new HashMap<>(); map.put(1, -1); // Initial product is 1 at index -1 for (int i = 0; i < nums.length; i++) { product *= nums[i]; if (map.containsKey(product / targetProduct)) { int length = i - map.get(product / targetProduct); maxLength = Math.max(maxLength, length); } if (!map.containsKey(product)) { map.put(product, i); } } return maxLength; } public static void main(String[] args) { int[] nums = {1, 2, 3, 4, 5}; int targetProduct = 20; int maxLength = findMaxSubarrayLength(nums, targetProduct); System.out.println("Maximum subarray length with target product " + targetProduct + ": " + maxLength); } }
In this program, the `findMaxSubarrayLength` method takes an array of integers (`nums`) and a target product (`targetProduct`) as input. It uses a sliding window approach along with a HashMap to keep track of the product and its corresponding index. The program iterates over the array, calculating the cumulative product at each step.
If the product divided by the target product is present in the HashMap, it means we have found a subarray with the desired product. The length of this subarray is calculated and compared with the maxLength to update the maximum length encountered so far.
The HashMap is used to store the product and its index. This allows us to quickly check if a product has been encountered before and find the starting index of the subarray with the desired product.
Finally, the `main` method demonstrates how to use the `findMaxSubarrayLength` method with a sample input array and target product. The result is then printed to the console.