fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.HashSet;
  5.  
  6. class Solution {
  7. public int maxOperations(int[] nums) {
  8. // Count occurrences of each number
  9. Map<Integer, Integer> countMap = new HashMap<>();
  10. for (int num : nums) {
  11. countMap.put(num, countMap.getOrDefault(num, 0) + 1);
  12. }
  13.  
  14. // Generate all unique pair sums
  15. Set<Integer> uniqueSums = new HashSet<>();
  16. int n = nums.length;
  17. for (int i = 0; i < n; i++) {
  18. for (int j = i + 1; j < n; j++) {
  19. uniqueSums.add(nums[i] + nums[j]);
  20. }
  21. }
  22.  
  23. int maxPairs = 0;
  24.  
  25. // Count pairs for each unique sum using the precomputed counts
  26. for (int k : uniqueSums) {
  27. maxPairs = Math.max(maxPairs, countPairsForK(countMap, k));
  28. }
  29.  
  30. return maxPairs;
  31. }
  32.  
  33. private int countPairsForK(Map<Integer, Integer> countMap, int k) {
  34. int pairCount = 0;
  35.  
  36. for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
  37. int num = entry.getKey();
  38. int partner = k - num;
  39.  
  40. if (countMap.containsKey(partner)) {
  41. if (num == partner) {
  42. // If both numbers are the same, use combination formula nC2
  43. pairCount += entry.getValue() / 2;
  44. } else if (num < partner) { // To avoid double counting
  45. // Count the pairs using the minimum of the counts of the two numbers
  46. pairCount += Math.min(entry.getValue(), countMap.get(partner));
  47. }
  48. }
  49. }
  50.  
  51. return pairCount;
  52. }
  53.  
  54. public static void main(String[] args) {
  55. Solution solution = new Solution();
  56. // Example input
  57. int[] nums = {1, 2, 3, 4, 3, 2, 1};
  58. int result = solution.maxOperations(nums);
  59. System.out.println(result); // Output the maximum number of pairs
  60. }
  61. }
  62.  
Success #stdin #stdout 0.09s 54576KB
stdin
Standard input is empty
stdout
3