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. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int arr[] ={1, 2, 3, 4, 5, -1, -4}; int k =9;
  13. HashMap<Integer,Integer>map = new HashMap<>();
  14. map.put(0,-1);
  15. int cs =0; int[]min1 ={0,arr.length}; int[]max1 ={0,-1};
  16. for(int j =0; j< arr.length; j++){
  17. cs += arr[j];
  18. if(!map.containsKey(cs)){map.put(cs,j);}
  19. int temp = cs-k;
  20. if(map.containsKey(temp)){
  21. int lo = map.get(temp); int top = j;
  22. if(top - lo <= min1[1]-min1[0]){min1[0]= lo+1; min1[1]= top;}
  23. if(top - lo >= max1[1]-max1[0]){max1[0]= lo+1; max1[1]= top;}
  24. }
  25. }
  26. System.out.println(" max ==>"+ max1[1]+" "+max1[0]);
  27. System.out.println(" min ==>"+ min1[1]+" "+min1[0]);
  28. }
  29. }
Success #stdin #stdout 0.14s 55476KB
stdin
Standard input is empty
stdout
 max ==>6  1
 min ==>4  3