面试题 16.10. 生存人数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int maxAliveYear(int[] birth, int[] death) {
int[] years = new int[102];
for (int i = 0; i < birth.length; i++) {
years[birth[i] - 1900]++;
years[death[i] + 1 - 1900]--;
}

// 最大前缀和对应的偏移量表示最大生存人数的年份
int preSum = 0, maxPreSum = 0, offset = 0;
for (int i = 0; i < years.length; i++) {
preSum += years[i];
if (preSum > maxPreSum) {
maxPreSum = preSum;
offset = i;
}
}

return 1900 + offset;
}
}

References

面试题 16.10. 生存人数