Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 14b96a5

Browse files
Add solution for Sliding Window Maximum
1 parent 050fcf7 commit 14b96a5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ Algorithm exercises from LeetCode implemented in Java v11.
8888
- Binary Subarrays With Sum | [Problem](https://leetcode.com/problems/binary-subarrays-with-sum) | [Solution](src/solutions/BinarySubarraysWithSum.java)
8989
- Maximum Points You Can Obtain from Cards | [Problem](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards) | [Solution](src/solutions/MaximumPointsFromCards.java)
9090
- Longest Substring Without Repeating Characters | [Problem](https://leetcode.com/problems/longest-substring-without-repeating-characters) | [Solution](src/solutions/LongestSubstringWithoutRepeatingCharacters.java)
91+
- Sliding Window Maximum | [Problem](https://leetcode.com/problems/sliding-window-maximum) | [Solution](src/solutions/SlidingWindowMaximum.java)
9192

9293
### Recursion
9394
- Closest Binary Search Tree Value | [Problem](https://leetcode.com/problems/closest-binary-search-tree-value)

‎src/solutions/SlidingWindowMaximum.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package solutions;
2+
3+
import java.util.*;
4+
5+
// [Problem] https://leetcode.com/problems/sliding-window-maximum
6+
class SlidingWindowMaximum {
7+
// Sliding window with Deque
8+
// O(n) time, O(k) space
9+
public int[] maxSlidingWindow(int[] nums, int k) {
10+
int n = nums.length;
11+
int[] max = new int[n - k + 1];
12+
Deque<Integer> windowIndices = new ArrayDeque<>();
13+
for (int i = 0; i < n; i++) {
14+
int maxIndex = i - k + 1;
15+
if (!windowIndices.isEmpty() && windowIndices.peek() < maxIndex) {
16+
windowIndices.poll();
17+
}
18+
while (!windowIndices.isEmpty() && nums[windowIndices.peekLast()] < nums[i]) {
19+
windowIndices.pollLast();
20+
}
21+
windowIndices.add(i);
22+
if (maxIndex >= 0) {
23+
max[maxIndex] = nums[windowIndices.peek()];
24+
}
25+
}
26+
return max;
27+
}
28+
29+
// Test
30+
public static void main(String[] args) {
31+
SlidingWindowMaximum solution = new SlidingWindowMaximum();
32+
33+
int[] input = {1, 3, -1, -3, 5, 3, 6, 7};
34+
int[] expectedOutput = {3, 3, 5, 5, 6, 7};
35+
int[] actualOutput = solution.maxSlidingWindow(input, 3);
36+
37+
System.out.println("Test passed? " + Arrays.equals(expectedOutput, actualOutput));
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /