fork download
  1. import java.util.HashMap;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] A = {15, 10, 5, 2, 7, 1, 9, 8, 7};
  6. int k = 15;
  7. System.out.println(countShortestSubarrays(A, k));
  8. }
  9.  
  10.  
  11. public static int countShortestSubarrays(int[] A, int k) {
  12. HashMap<Integer, Integer> sumIndexMap = new HashMap<>();
  13. int sum = 0, minLength = Integer.MAX_VALUE, count = 0;
  14. sumIndexMap.put(0,0);
  15. //because we do containskey(0)
  16. //since the logic sum-k==0 means we found a sum==k
  17. //if it doesnt exist already in map then the first sum==k will not be considered
  18. for (int i = 0; i < A.length; i++) {
  19. sum += A[i];
  20. if (sumIndexMap.containsKey(sum - k)) {
  21. int length = i - sumIndexMap.get(sum - k)+1;
  22. if (length < minLength) {
  23. minLength = length;
  24. count = 1; // Reset count for the new shortest length
  25. } else if (length == minLength) {
  26. count++; // Increment count for the same length
  27. }
  28. }
  29. sumIndexMap.put(sum, i); // Store the index of the current sum
  30. }
  31.  
  32. return (minLength == Integer.MAX_VALUE) ? 0 : count;
  33. }
  34. }
  35.  
Success #stdin #stdout 0.09s 54448KB
stdin
Standard input is empty
stdout
1