Maximum Length Subarray with Given Sum
This program finds maximum length subarray with sum equal to target.
Problem Statement
Write a Java program to find maximum length subarray with sum equal to 10.
Source Code
| 1 | import java.util.HashMap; |
| 2 | public class MaxLengthSubarraySum { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Max Length Subarray Sum"); |
| 5 | int[] arr = {1,2,3,4,2,1,3}; |
| 6 | int target=10; |
| 7 | HashMap<Integer,Integer> map = new HashMap<>(); |
| 8 | int sum=0, maxLen=0; |
| 9 | for(int i=0;i<arr.length;i++){ |
| 10 | sum+=arr[i]; |
| 11 | if(sum==target) maxLen=i+1; |
| 12 | if(map.containsKey(sum-target)){ |
| 13 | maxLen=Math.max(maxLen,i-map.get(sum-target)); |
| 14 | } |
| 15 | if(!map.containsKey(sum)) map.put(sum,i); |
| 16 | } |
| 17 | System.out.println("Maximum length subarray with sum "+target+" = "+maxLen); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Max Length Subarray Sum Maximum length subarray with sum 10 = 4
Explanation
A HashMap stores each prefix sum along with its earliest occurring index, and the current sum is checked against the target and against sum-target to find valid subarrays, updating the maximum length found, demonstrating efficient subarray length calculation.