fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /**
  8.  * Created by nikoo28 on 7/5/17.
  9.  */
  10. class TwoCharacters {
  11.  
  12. /*
  13. Code obtained from studyalgorithms.com
  14. Feel free to copy, but please acknowledge wherever possible
  15. */
  16. public static final int NUM_LETTERS = 26;
  17.  
  18. public static void main(String[] args) {
  19.  
  20. /* Save input */
  21. Scanner scan = new Scanner(System.in);
  22. int length = scan.nextInt();
  23. String str = scan.next();
  24. scan.close();
  25.  
  26. /* Edge case */
  27. if (length <= 1) {
  28. System.out.println(0);
  29. return;
  30. }
  31.  
  32. /* Create arrays representing the 26^2 subproblems */
  33. int[][] pair = new int[NUM_LETTERS][NUM_LETTERS];
  34. int[][] count = new int[NUM_LETTERS][NUM_LETTERS];
  35.  
  36. for (int i = 0; i < length; i++) {
  37. char letter = str.charAt(i);
  38. int letterNum = letter - 'a';
  39.  
  40. /* Update row */
  41. for (int col = 0; col < NUM_LETTERS; col++) {
  42. if (pair[letterNum][col] == letter) {
  43. count[letterNum][col] = -1;
  44. }
  45. if (count[letterNum][col] != -1) {
  46. pair[letterNum][col] = letter;
  47. count[letterNum][col]++;
  48. }
  49. }
  50.  
  51. /* Update column */
  52. for (int row = 0; row < NUM_LETTERS; row++) {
  53. if (pair[row][letterNum] == letter) {
  54. count[row][letterNum] = -1;
  55. }
  56. if (count[row][letterNum] != -1) {
  57. pair[row][letterNum] = letter;
  58. count[row][letterNum]++;
  59. /*
  60. Code obtained from studyalgorithms.com
  61. Feel free to copy, but please acknowledge wherever possible
  62. */
  63. }
  64. }
  65. }
  66.  
  67. /* Find max in "count" array */
  68. int max = 0;
  69. for (int row = 0; row < NUM_LETTERS; row++) {
  70. for (int col = 0; col < NUM_LETTERS; col++) {
  71. max = Math.max(max, count[row][col]);
  72. }
  73. }
  74. System.out.println(max);
  75. }
  76.  
  77. }
Success #stdin #stdout 0.08s 4386816KB
stdin
10
beabeefeab
stdout
5