Files
HackerRank-Solutions/Java/Data Structures/Java Dequeue/Solution.java
T

50 lines
1.5 KiB
Java
Raw Normal View History

2017-02-18 23:43:07 -06:00
// Author: Rodney Shaghoulian
// Github: github.com/rshaghoulian
// HackerRank: hackerrank.com/rshaghoulian
import java.util.Scanner;
import java.util.ArrayDeque;
import java.util.HashMap;
2017-04-09 19:12:53 -05:00
// Why not use just a HashMap instead of both a HashMap and an ArrayDeque?
// Well, an ArrayDeque helps keep the ordering of elements. Although the
// elements are also in our HashMap, they is no ordering to the elements
// in the HashMap since it's just a set.
2017-03-18 22:17:22 -05:00
// Time Complexity: O(n)
// Space Complexity: O(n)
2017-04-09 19:12:53 -05:00
2017-02-18 23:43:07 -06:00
public class test {
2017-04-09 19:12:53 -05:00
public static void main(String [] args) {
2017-02-18 23:43:07 -06:00
HashMap<Integer, Integer> map = new HashMap<>();
2017-04-09 19:12:53 -05:00
ArrayDeque<Integer> deque = new ArrayDeque<>();
2017-02-18 23:43:07 -06:00
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
2017-04-05 18:42:35 -05:00
int m = scan.nextInt();
int max = 0;
2017-02-21 00:05:09 -06:00
for (int i = 0; i < n; i++) {
/* Remove old value (if necessary) */
if (i >= m) {
2017-04-26 16:15:39 -07:00
int old = deque.removeFirst();
2017-02-21 00:05:09 -06:00
if (map.get(old) == 1) {
map.remove(old);
} else {
2017-03-18 22:17:22 -05:00
map.merge(old, -1, Integer::sum);
2017-02-21 00:05:09 -06:00
}
2017-02-18 23:43:07 -06:00
}
2017-03-18 22:17:22 -05:00
2017-02-18 23:43:07 -06:00
/* Add new value */
int num = scan.nextInt();
2017-04-26 16:15:39 -07:00
deque.addLast(num);
2017-03-18 22:17:22 -05:00
map.merge(num, 1, Integer::sum);
2017-02-18 23:43:07 -06:00
max = Math.max(max, map.size());
}
2017-02-21 00:05:09 -06:00
scan.close();
2017-02-18 23:43:07 -06:00
System.out.println(max);
}
}