2342. 数位和相等数对的最大和

2342. 数位和相等数对的最大和

解法一: 哈希, 贪心

go
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
func maximumSum(nums []int) int {
maxSumMap := make(map[int]int)
ans := -1
for _, num := range nums {
numSum := calcNumSum(num)
if maxNum, exists := maxSumMap[numSum]; exists {
if maxNum < num {
maxSumMap[numSum] = num
}
ans = max(ans, maxNum + num)
} else {
maxSumMap[numSum] = num
}
}
return ans
}

func calcNumSum(num int) int {
sum := 0
for num != 0 {
sum += num % 10
num /= 10
}
return sum
}

func max(num1, num2 int) int {
if num1 >= num2 {
return num1
}
return num2
}
作者

wuhunyu

发布于

2023-11-18

更新于

2023-11-18

许可协议