fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class CustomArray {
  8. public static void findSubArrayWithSum(int[] arr, int sum) {
  9. Map<Integer, Integer> cumulativeSumWithIndex = new HashMap<>();
  10. cumulativeSumWithIndex.put(0, -1);
  11. int cumulativeSum = 0;
  12. for (int index = 0; index < arr.length; index++) {
  13. cumulativeSum += arr[index];
  14. if (cumulativeSumWithIndex.get(cumulativeSum - sum) != null) {
  15. int startIndex = cumulativeSumWithIndex.get(cumulativeSum - sum) + 1;
  16. System.out.println("StartIndex: " + startIndex);
  17. System.out.println("EndIndex: " + index);
  18. break;
  19. }
  20. cumulativeSumWithIndex.put(cumulativeSum, index);
  21. }
  22. }
  23.  
  24. public static void main(String[] args) {
  25. CustomArray array = new CustomArray();
  26. int[] arr = {1, -1, 3, 5, 2};
  27. int expectedSum = 8;
  28. findSubArrayWithSum(arr, expectedSum);
  29. }
  30. }
Success #stdin #stdout 0.04s 2184192KB
stdin
Standard input is empty
stdout
StartIndex: 2
EndIndex: 3