Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- // Given a sequence of integers and a size k,
- // print the minimum number for every sliding window of size k
- namespace SlidingMinimum
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- // test(new int[]{4, 5, 1, 7, 3, -1, 2}, 2);
- test(new int[]{1, 2, 3, 1, 2, 3}, 3);
- }
- static void test(int[] arr, int k) {
- printSlidingMinimum(arr, k);
- }
- // Asssumes k > 1
- static void printSlidingMinimum(int[] arr, int k) {
- if (k < 1) {
- Console.WriteLine("k should be greater than 1");
- return;
- }
- var minQueue = new Queue<int>();
- bool shouldPrintMinimum = false;
- minQueue.Enqueue(arr[0]);
- for(int i = 1; i < arr.Length; i++) {
- if (i == k - 1) {
- shouldPrintMinimum = true;
- }
- var current = arr[i];
- if (minQueue.Count == k) {
- var dequeuedValue = minQueue.Dequeue();
- }
- if (current < minQueue.Peek()) {
- while (minQueue.Count > 0) {
- var dequeuedValue = minQueue.Dequeue();
- }
- }
- minQueue.Enqueue(current);
- if (shouldPrintMinimum) {
- Console.WriteLine(minQueue.Peek());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement