This page explains Java solution to problem Sliding Window Maximum
using TreeMap
data structure.
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
package com.vc.hard;
import java.util.*;
class SlidingWindowMaximum {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0) return new int[0];
TreeMap<Integer, Integer> treeMap = new TreeMap<>();
for(int i = 0; i < k; i++) {
treeMap.put(nums[i], treeMap.getOrDefault(nums[i], 0) + 1);
}
int n = nums.length;
int[] res = new int[n - k + 1];
for(int i = k; i < n; i++) {
//Take max element from the treeMap
res[i - k] = treeMap.lastKey();
//Remove (i - k)th element from treeMap
int toRemove = nums[i - k];
treeMap.put(toRemove, treeMap.getOrDefault(toRemove, 0) - 1);
if(treeMap.get(toRemove) == 0) treeMap.remove(toRemove);
//Add ith element into treeMap
int toAdd = nums[i];
treeMap.put(toAdd, treeMap.getOrDefault(toAdd, 0) + 1);
}
res[n - k] = treeMap.lastKey();
return res;
}
}
O(N * log(K)) Where
N is total number of elements in an input array
K is Window size.
O(N) Where
N is total number of elements in an input array