-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2342MaxSumOfPair.java
More file actions
49 lines (42 loc) · 1.28 KB
/
Q2342MaxSumOfPair.java
File metadata and controls
49 lines (42 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
@b-knd (jingru) on 18 July 2022 08:58:00
*/
/*
Concept:
- Using hashmap, store sum of digit with its respective max value (continue updating)
- Variable max to store current maximum sum
- Loop through array nums
-- update maximum value by adding current value and maximum value in hashmap after comparing
-- initiate or update hashmap by comparing maximum value for that number of digit
- Return variable max
*/
import java.util.HashMap;
class Q2342MaxSumOfPair {
public int maximumSum(int[] nums) {
HashMap<Integer,Integer> hm = new HashMap<>();
int max = -1;
for (int num : nums) {
//current sum of digits
int temp = sumDigit(num);
//if map contains the same number of digit, update ans and hashmap
if (hm.containsKey(temp)) {
max = Math.max(max, num + hm.get(temp));
hm.put(temp, Math.max(num, hm.get(temp)));
} else {
// Add the value in the map
hm.put(temp, num);
}
}
//return max sum
return max;
}
//method to find sum of digit of an integer
public int sumDigit(int n){
int sum = 0;
while(n > 0){
sum += n % 10;
n /= 10;
}
return sum;
}
}