Skip to content

Commit 6cdf28d

Browse files
authored
Merge pull request #3373 from ChiragSharma0208/add-solution
Create: 0895-maximum-frequency-stack.java
2 parents e40213d + c22222f commit 6cdf28d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Diff for: java/0895-maximum-frequency-stack.java

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class FreqStack {
2+
HashMap<Integer, Integer> freq = new HashMap<>();
3+
HashMap<Integer, Stack<Integer>> m = new HashMap<>();
4+
int maxfreq = 0;
5+
6+
public void push(int x) {
7+
int f = freq.getOrDefault(x, 0) + 1;
8+
freq.put(x, f);
9+
maxfreq = Math.max(maxfreq, f);
10+
if (!m.containsKey(f)) m.put(f, new Stack<Integer>());
11+
m.get(f).add(x);
12+
}
13+
14+
public int pop() {
15+
int x = m.get(maxfreq).pop();
16+
freq.put(x, maxfreq - 1);
17+
if (m.get(maxfreq).size() == 0) maxfreq--;
18+
return x;
19+
}
20+
}

0 commit comments

Comments
 (0)