HZOJ-242:最大平均值

#include 
#define MAX 100000

long long a[MAX + 5], b[MAX + 5] = { 0 };


int check(long long* a, int n, int M, int mid) {
	for (int i = 1; i <= n; i++) b[i] = a[i] - mid + b[i - 1];
	long long c = 0;
	for (int i = M; i <= n; i++) {
		c = c > b[i - M] ? b[i - M] : c;
		if (b[i] - c >= 0) return 1;
	}
	return 0;
}

int solve(long long* a, int max, int n, int M) {
	int head = 0, tail = max, mid;
	while (head < tail) {
		mid = (head + tail + 1) / 2;
		if (check(a, n, M, mid)) head = mid;
		else tail = mid - 1;
	}
	return head;
}

int main() {
	int N, M, max = 0;
	scanf("%d%d", &N, &M);
	for (int i = 1; i <= N; i++) {
		int x;
		scanf("%d", &x);
		a[i] = x * 1000;
		if (a[i] > max) max = a[i];
	}
	printf("%d", solve(a, max, N, M));
	return 0;
}

你可能感兴趣的:(算法题,算法,数据结构)