Guest User

Untitled

a guest
Nov 9th, 2022
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class MostFrequent {
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7.  
  8. int n = Integer.parseInt(scanner.nextLine());
  9.  
  10. int[] elements = new int[n];
  11. for (int i = 0; i < elements.length; i++) {
  12. elements[i] = Integer.parseInt(scanner.nextLine());
  13. }
  14.  
  15. //SORTING the integers
  16. for (int i = 0; i < elements.length; i++) {
  17. for (int j = i+1; j < elements.length; j++) {
  18. int temporary = 0;
  19. if (elements[i] > elements[j]) {
  20. temporary = elements[i];
  21. elements[i] = elements[j];
  22. elements[j] = temporary;
  23. }
  24. }
  25. }
  26.  
  27. int count = 1;
  28. int maxCount = 0;
  29. int mostCommonNumber = 0;
  30.  
  31. for (int i = 0; i < elements.length + 1; i++) {
  32. if (i == elements.length - 1) {
  33. break;
  34. }
  35. if (elements[i] == elements[i+1]) {
  36. count++;
  37. if (i == elements.length - 2 && maxCount < count) {
  38. maxCount = count;
  39. mostCommonNumber = elements[i];
  40. }
  41. } else {
  42. if (maxCount < count) {
  43. maxCount = count;
  44. mostCommonNumber = elements[i];
  45. }
  46. count = 1;
  47. }
  48. }
  49.  
  50. System.out.printf("%d (%d times)", mostCommonNumber, maxCount);
  51. }
  52. }
  53.  
Add Comment
Please, Sign In to add comment