OD C卷 - 贪吃的猴子
贪吃的猴子 (200)
- 一只猴子获取香蕉,只能从数组(元素为香蕉数)的头部或者尾部开始获取;
- 最多只能取n次;
- 求最多获取的香蕉数;
输入描述:
第一行输入数组长度m;
第二行输入数组的数据;
第三行为获取次数n;
输出描述:
获取的最大数值
示例1
输入:
7
1 2 2 7 3 6 1
3
输出:
10
示例2
输入:
3
1 2 3
3
输出:
6
示例3
输入:
4
4 2 2 3
2
输出:
7
思路:
- 双指针,先从开头依次取n次,并求和 result;
- 开头取 依次舍去最后一次,改从末尾取,求和并与result比较,取最大值;
- 依次类推
# 输入
arr_len = int(input().strip())
arr_list = list(map(int, input().strip().split()))
n_times = int(input().strip())
result = 0
for i in range(n_times):
result += arr_list[i]
temp = result
i = n_times - 1
while i >= 0:
temp = temp - arr_list[i] + arr_list[i - n_times]
if temp > result:
result = temp
i -= 1
print(result)