fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5.  
  6. int[] arr = {1, 2, 3, 7, 5};
  7. int k = 12;
  8.  
  9. int[] ans =Solve(arr, k);
  10.  
  11. System.out.println("Largest Length = " + ans[0]);
  12. System.out.println("Smallest Length = " + ans[1]);
  13. }
  14.  
  15. public static int[] Solve(int[] arr, int k) {
  16. HashMap<Integer, Integer> HM = new HashMap<>();
  17. HM.put(0, -1);
  18. int prefix = 0;
  19. int maxLen = 0;
  20. int minLen = Integer.MAX_VALUE;
  21.  
  22. for (int j = 0; j < arr.length; j++) {
  23.  
  24. prefix += arr[j];
  25.  
  26.  
  27. if (HM.containsKey(prefix - k)) {
  28.  
  29. int i = HM.get(prefix - k) + 1;
  30. int currLen = j - i + 1;
  31. maxLen = Math.max(maxLen, currLen);
  32. minLen = Math.min(minLen, currLen);
  33. }
  34. HM.putIfAbsent(prefix, j);
  35. }
  36. if (minLen == Integer.MAX_VALUE) {
  37. minLen = 0;
  38. }
  39.  
  40. return new int[]{maxLen, minLen};
  41. }
  42. }
  43.  
Success #stdin #stdout 0.11s 55588KB
stdin
Standard input is empty
stdout
Largest Length = 3
Smallest Length = 2