Finding the maximum subarray length with given sum.
Below is a Java program that finds the maximum subarray length with a given sum:
public class MaximumSubarrayLength { public static int findMaxLength(int[] nums, int targetSum) { int maxLength = 0; int sum = 0; HashMap<Integer, Integer> sumMap = new HashMap<>(); sumMap.put(0, -1); // To handle cases where the subarray starts from index 0 for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (sumMap.containsKey(sum - targetSum)) { int subarrayLength = i - sumMap.get(sum - targetSum); maxLength = Math.max(maxLength, subarrayLength); } if (!sumMap.containsKey(sum)) { sumMap.put(sum, i); } } return maxLength; } public static void main(String[] args) { int[] nums = {1, -2, 3, 4, -5, 6, 7}; int targetSum = 5; int maxLength = findMaxLength(nums, targetSum); System.out.println("Maximum subarray length with sum " + targetSum + ": " + maxLength); } }
In this program, we iterate through the given array `nums` and maintain a running sum `sum` of the elements encountered so far. We also use a HashMap `sumMap` to store the sum and its corresponding index.
At each iteration, we check if `sum – targetSum` exists in `sumMap`. If it does, it means we have found a subarray with the target sum. We calculate the length of the subarray and update `maxLength` if the current length is greater than the previous maximum length.
Finally, we return `maxLength` as the maximum subarray length with the given sum.
In the `main` method, we provide a sample input array `nums` and the target sum `targetSum`. The program then calls the `findMaxLength` method and prints the result.