给你一个下标从 0 开始的数组
nums
,数组中的元素都是 正 整数。请你选出两个下标i
和j
(i != j
),且nums[i]
的数位和 与nums[j]
的数位和相等。请你找出所有满足条件的下标
i
和j
,找出并返回nums[i] + nums[j]
可以得到的 最大值 。
- public class Two {
- public static void main(String[] args) {
- Two two = new Two();
- System.out.println(two.maximumSum(new int[]{18,43,36,13,7}));
- System.out.println(two.maximumSum(new int[]{10,12,19,14}));
- }
- public int maximumSum(int[] nums) {
- Map
> data = new HashMap<>(); - for (int i = 0; i < nums.length; i++){
- int num = numSum(nums[i]);
- List
temp = data.getOrDefault(num, new ArrayList<>()); - temp.add(nums[i]);
- data.put(num, temp);
- }
- int maxSum = -1;
- for (List
list : data.values()){ - int size = list.size();
- if(size < 2){
- continue;
- }
- Collections.sort(list);
- maxSum = Math.max(maxSum, list.get(size - 1) + list.get(size - 2));
- }
- return maxSum;
- }
- public int numSum(int num){
- int sum = 0;
- while (num > 0){
- sum += num % 10;
- num = num / 10;
- }
- return sum;
- }
- }