Created
July 13, 2015 00:02
-
-
Save VegaFromLyra/89a9f1c4e35c65b7903a to your computer and use it in GitHub Desktop.
Sliding minimum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment