fork download
  1. // Online Java Compiler (Editor)
  2. // Write and run Java online using this editor.
  3. import java.util.*;
  4. class Main {
  5. public static int func(int a[],int k){
  6. int n = a.length;
  7. HashMap<Integer,Integer>map = new HashMap<>();
  8. ArrayList<Integer>list = new ArrayList<>();
  9. map.put(0,-1);
  10. int p[] = new int[n];
  11. p[0] = a[0];
  12. for(int i=1;i<n;i++){
  13. p[i] = p[i-1] + a[i];
  14. }
  15.  
  16. int maxilen = Integer.MIN_VALUE;
  17. for(int j=0;j<n;j++){
  18. int req = p[j]-k;
  19. if(map.containsKey(req)){
  20. int i = map.getOrDefault(req,0)+1;
  21. int len = j-i+1;
  22. list.add(len);
  23. maxilen = Math.max(maxilen,len);
  24. }
  25. if(!map.containsKey(p[j])){
  26. map.put(p[j],j);
  27. }
  28. }
  29. int maxvalue = list.get(0);
  30. for(int i=1;i<list.size();i++){
  31. if(list.get(i) > maxvalue){
  32. maxvalue = list.get(i);
  33. }
  34. }
  35. int count = 0;
  36. for(int i=0;i<list.size();i++){
  37. if(list.get(i) == maxvalue){
  38. count++;
  39. }
  40. }
  41. return count;
  42. // if(maxilen == Integer.MIN_VALUE){
  43. // return 0;
  44. // } else{
  45. // return maxilen;
  46. // }
  47. }
  48. public static void main(String[] args) {
  49. int a[] = {3,2,3,3,2,8};
  50. int ans = func(a,8);
  51. System.out.println(ans);
  52. }
  53. }
Success #stdin #stdout 0.07s 16500KB
stdin
Standard input is empty
stdout
3