2019校招网易-瞌睡的小易要拿到最大兴趣值
算法思路:从头到尾遍历,清醒状态则加上,瞌睡状态则:其后 k 个值加上以及剩余个数的和,然后判断值是否比当前最大值大,若大则更新最大值;
另一种算法思路:加上所有清醒状态的值 s1,遍历瞌睡状态的值,则其后 k 个值中瞌睡状态的值加上为 s2,若 s2 大于最大值则更新最大值,遍历完瞌睡状态的值,则最终结果为 s1+最大值,这种思路也是一种解决方案!
#include <iostream>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int *a = new int[n];
int *t = new int[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n; i++) {
cin >> t[i];
}
int maxInterests = 0, interests = 0;
for (int i = 0; i < n; i++) {
int temp = 0;
if (t[i] == 1) {
interests += a[i];
}
else {
temp = interests;
for (int j = i; j < n&&j < i + k; j++) {
interests += a[j];
}
for (int j = i + k; j < n; j++) {
if (t[j] == 1) {
interests += a[j];
}
}
if (interests > maxInterests) {
maxInterests = interests;
}
interests = temp;
}
if (temp == 0 && interests > maxInterests) {
maxInterests = interests;
}
}
cout << maxInterests << endl;
system("pause");
return 0;
}