fork download
  1. package myJava;
  2.  
  3. import java.util.ArrayDeque;
  4.  
  5. class SlidingWindow {
  6.  
  7. int[] maxsDeque(int[] arr, int k) {
  8.  
  9. //Bounds check
  10. if( k > arr.length || k < 1)
  11. return new int[]{};
  12.  
  13. int windows = arr.length - k + 1; //number of windows
  14.  
  15. ArrayDeque<Integer> deck = new ArrayDeque<Integer>();
  16. int[] maximums = new int[windows];
  17.  
  18. for (int i = 0; i < arr.length; i++) {
  19. if( i >= k )
  20. maximums[i-k] = arr[deck.getFirst()];
  21.  
  22. while (!deck.isEmpty() && arr[i] >= arr[deck.getLast()])
  23. deck.pollLast();
  24. while (!deck.isEmpty() && deck.getFirst() <= (i-k))
  25. deck.pollFirst();
  26. deck.addLast(i);
  27. }
  28. maximums[windows-1] = arr[deck.getFirst()];
  29. return maximums;
  30. }
  31.  
  32. }
  33.  
  34.  
  35. import static org.junit.Assert.*;
  36. import org.junit.Before;
  37. import org.junit.BeforeClass;
  38. import org.junit.Test;
  39.  
  40. public class SlidingWindowTest {
  41.  
  42. SlidingWindow win;
  43.  
  44. @Before
  45. public void setUp() throws Exception {
  46. win = new SlidingWindow();
  47. }
  48.  
  49. @Test
  50. public void testMaxsDeque() {
  51. assertArrayEquals(
  52. new int[]{11,6,6,9,9,9,8,15},
  53. win.maxsDeque(new int[]{ 11, -2, 5, 6, 0, 9, 8, -1, 2, 15 }, 3));
  54.  
  55. assertArrayEquals(
  56. new int[]{6,6,9,9,9,8,15},
  57. win.maxsDeque(new int[]{ -2, 5, 6, 0, 9, 8, -1, 2, 15 }, 3));
  58.  
  59. assertArrayEquals(
  60. new int[]{500},
  61. win.maxsDeque(new int[]{ 500 }, 1));
  62.  
  63. assertArrayEquals(
  64. new int[]{6,6,6},
  65. win.maxsDeque(new int[]{ 6,6,6 }, 1));
  66. assertArrayEquals(
  67. new int[]{6},
  68. win.maxsDeque(new int[]{ 6,6,6 }, 3));
  69.  
  70. assertArrayEquals(
  71. new int[]{},
  72. win.maxsDeque(new int[]{ 6 }, 2));
  73. assertArrayEquals(
  74. new int[]{},
  75. win.maxsDeque(new int[]{ 6 }, 0));
  76. }
  77.  
  78. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Warning: Binary file SlidingWindow contains myJava.SlidingWindow
spoj: The program compiled successfully, but main class was not found.
      Main class should contain method: public static void main (String[] args).
stdout
Standard output is empty