gap between me and top algorithm experts

距离上一次打比赛要追溯到上个月leetcode cup 367,虽然第二题意外WA了四次,还是成功AK。秋招拿了4个offer,休息了一个多月。

今天无聊做了做每日一题,看完数据范围,设计好方法后,感觉我真是个天才,ac后看了灵神的题解,自愧不如。。。

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

my proposed method

要求数位和(digit sum)相等的数组元素中最大的数组元素和,看数据范围,\(nums[i] \in [1, 10^9]\),那么极限范围是999999999,数位和最大81,那我创建82个treemap,遍历完数组后,降序从treemap中找答案不就行了,easy

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
class Solution {
public int maximumSum(int[] nums) {
int n = nums.length, res = -1;
// nums最大1e9,9个9相加是81
// treemap中存放数位和相同的数组元素
TreeMap<Integer, Integer>[] maps = new TreeMap[82];
Arrays.setAll(maps, e -> new TreeMap<>());
for (int x : nums) {
int bitSum = 0, num = x;
while (num > 0) {
bitSum += num % 10;
num /= 10;
}
TreeMap<Integer, Integer> map = maps[bitSum];
map.put(x, map.getOrDefault(x, 0) + 1);
}
for (int i = 81; i >= 0; --i) {
TreeMap<Integer, Integer> map = maps[i];
int key1 = -1;
for (int key : map.descendingKeySet()) {
if (key1 == -1 && map.get(key) >= 2) {
res = Math.max(res, key * 2);
break;
}
else if (key1 == -1 && map.get(key) == 1)
key1 = key;
else if (key1 != -1) {
res = Math.max(res, key1 + key);
break;
}
}
}
return res;
}
}

expert solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def maximumSum(self, nums: List[int]) -> int:
ans = -1
mx = [0] * 82 # 至多 9 个 9 相加
for num in nums:
# s = sum(map(int, str(num)))
# 不转成 str,效率更高
s = 0
x = num
while x: # 枚举 num 的每个数位
s += x % 10
x //= 10
if mx[s]: # 说明左边也有数位和等于 s 的元素
ans = max(ans, mx[s] + num) # 更新答案的最大值
mx[s] = max(mx[s], num) # 维护数位和等于 s 的最大元素
return ans


gap between me and top algorithm experts
https://leopol1d.github.io/2023/11/18/gap-between-me-and-top-algorithm-experts/
作者
Leopold
发布于
2023年11月18日
许可协议