# 贪吃的猴子 – 华为OD统一考试（C卷）

OD统一考试（C卷）

### 示例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

``````

1<= numbers.length <= 100000

1<= numbers <= 100

1 <= N <= numbers.length

### 题解

#### C++

``````#include <iostream>
#include <vector>

using namespace std;

int main() {
int n;
cin >> n;
vector<int> numbers(n);
for(int i=0; i<n; i++) cin >> numbers[i];

int N;
cin >> N;
int tot = 0;
for(int i=0; i<N; i++) tot += numbers[i];

int rs = tot;

int l = N-1, r = n-1;
while(l >= 0) {
tot += numbers[r--] - numbers[l--];
rs = max(rs, tot);
}

cout << rs << endl;

return 0;
}
``````

#### Java

``````import java.util.Arrays;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] numbers = Arrays.stream(new int[n]).map(i -> in.nextInt()).toArray();
int N = in.nextInt();

// 左边选N个， 右侧选0个
int tot = Arrays.stream(numbers, 0, N).sum();

int rs = tot;
int l = N - 1, r = n - 1;

// 不断的尝试调整两边的元素选取个数, 找到最佳结果
while (l >= 0) {
tot += numbers[r--] - numbers[l--];
rs = Math.max(rs, tot);
}
System.out.println(rs);
}
}
``````

#### Python

``````n = int(input())
numbers = list(map(int, input().split()))
N = int(input())

tot = sum(numbers[i] for i in range(N))
rs = tot

r = n - 1
for l in range(N-1, -1, -1):
tot += numbers[r] - numbers[l]
rs = max(rs, tot)
r -= 1

print(rs)
``````

🙏整理题解不易， 如果有帮助到您，请给点个赞 ‍❤️‍ 和收藏 ⭐，让更多的人看到。🙏🙏🙏

THE END