华为OD机试 - 滑动窗口最大和

华为OD机试 - 滑动窗口最大和_第1张图片

滑动窗口的经典题型,重复题目

#include 
#include 
#include 

#define MAX(a,b) ((a) > (b) ? (a) : (b))
int main()
{
    int n;
    scanf("%d", &n);

    int *list = malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &list[i]);
    }
    int m;
    scanf("%d", &m);

    int sum = 0;
    int max;
    int left = 0, right = 0;
    while (right < n) {
        sum += list[right];
        right++;
        if (right - left < m) {
            continue;
        }
        
        if (left == 0) {
            max = sum;
        } else {
            max = MAX(max, sum);
        }
        sum -= list[left];
        left++;
    }

    printf("%d\n", max);
    return 0;
}

你可能感兴趣的:(华为OD机考真题(C,C++,python),华为od,算法,滑动窗口)