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,2,3};
  13. int target = 2;
  14.  
  15. System.out.println(countMajoritySubarrays(arr,target));
  16. }
  17.  
  18. static int countMajoritySubarrays(int[] nums, int target) {
  19. int n = nums.length;
  20.  
  21. int[] arr = new int[n];
  22.  
  23. for(int i =0;i<n;i++){
  24. if(nums[i] == target){
  25. arr[i] = 1;
  26.  
  27. }
  28. else{
  29. arr[i] = -1;
  30. }
  31. }
  32.  
  33. int[] prefix = new int[n];
  34.  
  35. prefix[0] = arr[0];
  36. for(int i=1;i<n;i++){
  37. prefix[i] = prefix[i-1] + arr[i];
  38. }
  39.  
  40. HashMap<Integer,Integer> map= new HashMap<>();
  41. map.put(0,1);
  42. int count = 0;
  43. for(int i = 0;i< n;i++){
  44.  
  45. int curr = prefix[i];
  46.  
  47. for(Map.Entry<Integer,Integer> entry : map.entrySet()){
  48.  
  49. if(entry.getKey() < curr){
  50. count = count + entry.getValue();
  51. }
  52. }
  53. map.put(curr,map.getOrDefault(curr,0)+1);
  54. }
  55. return count;
  56. }
  57. }
Success #stdin #stdout 0.1s 54628KB
stdin
Standard input is empty
stdout
5