【华为OD机试真题】找出通过车辆最多颜色
题目描述
在一个狭小的路口,每秒只能通过一辆车,假设车辆的颜色只有 3 种,找出 N 秒内经过的最多颜色的车辆数量。
三种颜色编号为0 ,1 ,2
输入描述
第一行输入的是通过的车辆颜色信息
[0,1,1,2] 代表4 秒钟通过的车辆颜色分别是 0 , 1 , 1 , 2
第二行输入的是统计时间窗,整型,单位为秒
输出描述
输出指定时间窗内经过的最多颜色的车辆数量。
测试样例1
输入
0 1 2 1
3
输出
2
说明
在 3 秒时间窗内,每个颜色最多出现 2 次。例如:[1,2,1]
测试样例2
输入
0 1 2 1
2
输出
1
说明
在 2 秒时间窗内,每个颜色最多出现1 次。
Python代码解析
def max_color_count_in_window(colors, window_size):
if window_size <= 0:
return 0
n = len(colors)
if n == 0:
return 0
# 用于统计每种颜色的数量
color_count = [0] * 3
max_count = 0
current_max_color_count = 0
# 初始化第一个窗口
for i in range(min(window_size, n)):
color_count[colors[i]] += 1
current_max_color_count = max(current_max_color_count, color_count[colors[i]])
max_count = current_max_color_count
# 滑动窗口
for i in range(window_size, n):
# 移除窗口左边的元素
left_color = colors[i - window_size]
color_count[left_color] -= 1
# 添加新元素到窗口右边
right_color = colors[i]
color_count[right_color] += 1
# 更新当前窗口的最大颜色数量
current_max_color_count = max(current_max_color_count, color_count[right_color])
# 更新全局的最大颜色数量
max_count = max(max_count, current_max_color_count)
return max_count
# 输入输出处理
input_colors = list(map(int, input().split()))
window = int(input())
print(max_color_count_in_window(input_colors, window))
#华为OD##华为OD机考##华为OD机试真题##华为OD机试算法题库##华为OD题库#