fork download
  1. import java.util.Scanner;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4.  
  5. class SubarrayLengthFinder {
  6.  
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9. int n = sc.nextInt();
  10. int[] arr = new int[n];
  11.  
  12. for (int i = 0; i < n; i++) {
  13. arr[i] = sc.nextInt();
  14. }
  15. int target = sc.nextInt();
  16.  
  17. Map<Integer, Integer> map1 = new HashMap<>();
  18. Map<Integer, Integer> map2 = new HashMap<>();
  19.  
  20. int prefixSum = 0;
  21. int maxLength = 0;
  22. int minLength = Integer.MAX_VALUE;
  23.  
  24. map1.put(0, -1);
  25. map2.put(0, -1);
  26.  
  27. for (int j = 0; j < n; j++) {
  28. prefixSum += arr[j];
  29.  
  30. int x = prefixSum - target;
  31.  
  32. if (map1.containsKey(x)) {
  33. int i = map1.get(x);
  34. int currentLength = j - i;
  35. if (currentLength > maxLength) {
  36. maxLength = currentLength;
  37. }
  38. }
  39.  
  40. if (map2.containsKey(x)) {
  41. int i = map2.get(x);
  42. int currentLength = j - i;
  43. if (currentLength < minLength) {
  44. minLength = currentLength;
  45. }
  46. }
  47.  
  48. map1.putIfAbsent(prefixSum, j);
  49. map2.put(prefixSum, j);
  50. }
  51.  
  52. System.out.println("Maximum Length: " + maxLength);
  53.  
  54. if (minLength == Integer.MAX_VALUE) {
  55. System.out.println("Minimum Length: 0");
  56. } else {
  57. System.out.println("Minimum Length: " + minLength);
  58. }
  59.  
  60. sc.close();
  61. }
  62. }
  63.  
Success #stdin #stdout 0.17s 59044KB
stdin
5
3 1 3 -2 2
4
stdout
Maximum Length: 4
Minimum Length: 2