fork download
  1. import java.util.*;
  2.  
  3. class Ideone {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. int k = sc.nextInt();
  8. int arr[] = new int[n];
  9. for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
  10.  
  11. HashMap<Integer,Integer> first = new HashMap<>();
  12. HashMap<Integer,Integer> last = new HashMap<>();
  13. int sum = 0, maxLen = 0, minLen = Integer.MAX_VALUE;
  14.  
  15. first.put(0,-1);
  16. last.put(0,-1);
  17.  
  18. for (int i = 0; i < n; i++) {
  19. sum += arr[i];
  20.  
  21. if (first.containsKey(sum - k)) {
  22. maxLen = Math.max(maxLen, i - first.get(sum - k));
  23. }
  24. if (last.containsKey(sum - k)) {
  25. minLen = Math.min(minLen, i - last.get(sum - k));
  26. }
  27.  
  28. if (!first.containsKey(sum)) first.put(sum,i);
  29. last.put(sum,i);
  30. }
  31.  
  32. System.out.println(maxLen + " " + (minLen == Integer.MAX_VALUE ? 0 : minLen));
  33. }
  34. }
Success #stdin #stdout 0.17s 58848KB
stdin
4
4
2
2
0
5
stdout
3 2