fork download
  1. // no of ways to divide the given array into 3 equal parts
  2. import java.util.*;
  3. public class Main
  4. {
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. int n=sc.nextInt();
  8. int[]nums = new int[n];
  9.  
  10. for(int i= 0;i<n;i++){
  11. nums[i]=sc.nextInt();
  12. }
  13. int tot_sum=0;
  14. for(int i=0;i<n;i++){
  15. tot_sum+=nums[i];
  16. }
  17. int lhs=0;
  18. int rhs=0;
  19. int count=0;
  20.  
  21. if(tot_sum%3 ==0){
  22. int y=tot_sum/3;
  23.  
  24. //I need current sum
  25. int current_sum=0;
  26.  
  27. HashMap<Integer,Integer>f = new HashMap<>();
  28.  
  29. for(int j=0;j<n-1;j++){
  30. lhs+=nums[j];
  31. rhs=tot_sum-lhs;
  32. current_sum+=nums[j];
  33.  
  34. if(lhs == 2*y && rhs ==y ){
  35. count=count + f.getOrDefault(current_sum/2,0) ;
  36. }
  37. f.put(current_sum,f.getOrDefault(current_sum,0)+1);
  38. }
  39. }
  40. System.out.print("Number of ways to divide in three equal parts :" + count);
  41. }
  42. }
Runtime error #stdin #stdout #stderr 0.13s 54600KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.Scanner.throwFor(Scanner.java:937)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at Main.main(Main.java:7)