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. if(list.isEmpty()){
  30. return 0;
  31. }
  32. int maxvalue = list.get(0);
  33. for(int i=1;i<list.size();i++){
  34. if(list.get(i) > maxvalue){
  35. maxvalue = list.get(i);
  36. }
  37. }
  38. int count = 0;
  39. for(int i=0;i<list.size();i++){
  40. if(list.get(i) == maxvalue){
  41. count++;
  42. }
  43. }
  44. return count;
  45. // if(maxilen == Integer.MIN_VALUE){
  46. // return 0;
  47. // } else{
  48. // return maxilen;
  49. // }
  50. }
  51. public static void main(String[] args) {
  52. int a[] = {3,2,3,3,2,8};
  53. int ans = func(a,8);
  54. System.out.println(ans);
  55. }
  56. }
Success #stdin #stdout 0.07s 16492KB
stdin
Standard input is empty
stdout
3