Cod sursa(job #97784)

Utilizator flionIonescu Ionut Florin flion Data 8 noiembrie 2007 19:09:56
Problema Secventa Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.1 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define nmax 100001

int N, K, i, bottomm, topm, bottomM, topM, ultm, ultM, max, AA;

short Vm[nmax], VM[nmax];

int main(void)
{
	short A[nmax], PM[nmax], Pm[nmax];

	max = -1;

	freopen("vila2.in", "r", stdin);
	freopen("vila2.out", "w", stdout);

	scanf("%d %d\n", &N, &K);
	K++;

	for (i = 1; i <= N; i++)
	{
		scanf("%d", AA);
		A[i] = AA;
	}

	for (i = 1, bottomm = bottomM = 0, topm = topM = -1, ultm = ultM = 0; i <= N - K + 1; i++)
	{
		while (ultm < i + K - 1 && ultm < N)
		{
			ultm++;

			while (topm >= bottomm && Vm[topm] >= A[ultm])
				topm--;

			topm++;

			Vm[topm] = A[ultm];
			Pm[topm] = ultm;
		}

		while (Pm[bottomm] < i)
			bottomm++;


		while (ultM < i + K - 1 && ultM < N)
		{
			ultM++;

			while (topM >= bottomM && VM[topM] <= A[ultM])
				topM--;

			topM++;

			VM[topM] = A[ultM];
			PM[topM] = ultM;
		}

		while (PM[bottomM] < i)
			bottomM++;

		if (VM[bottomM] - Vm[bottomm] > max)
			max = VM[bottomM] - Vm[bottomm];
	}

	printf("%d\n", max);

	return 0;
}