To find subarrays with a given sum in an array, you can use a sliding window approach. Here's a Java implementation:
import java.util.ArrayList;
import java.util.List;
public class SubarraysWithGivenSum {
public static List<List<Integer>> findSubarrays(int[] nums, int targetSum) {
List<List<Integer>> result = new ArrayList<>();
int n = nums.length;
int sum = 0;
int left = 0;
for (int right = 0; right < n; right++) {
sum += nums[right];
while (sum > targetSum && left <= right) {
sum -= nums[left++];
}
if (sum == targetSum) {
List<Integer> subarray = new ArrayList<>();
for (int i = left; i <= right; i++) {
subarray.add(nums[i]);
}
result.add(subarray);
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 4, 20, 3, 10, 5};
int targetSum = 33;
List<List<Integer>> subarrays = findSubarrays(nums, targetSum);
System.out.println("Subarrays with sum " + targetSum + ":");
for (List<Integer> subarray : subarrays) {
System.out.println(subarray);
}
}
}
In this implementation:
- We use a sliding window to find subarrays with the given sum.
- We maintain two pointers,
left
andright
, to define the current window. - We continuously expand the window by moving the
right
pointer until the sum of elements in the window exceeds the target sum. - If the sum of the current window equals the target sum, we add the subarray defined by the window to the result list.
- We continue this process until we reach the end of the array.
- We test the implementation with an example array and target sum and print the subarrays with the given sum.