Skip to content

Commit 6cfe27a

Browse files
committed
2025-01-08 v. 7.8.0: added "239. Sliding Window Maximum"
1 parent f1df9e9 commit 6cfe27a

File tree

4 files changed

+62
-1
lines changed

4 files changed

+62
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,3 +649,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
649649
| 115. Distinct Subsequences | [Link](https://leetcode.com/problems/distinct-subsequences/) | [Link](./lib/hard/115_distinct_subsequences.rb) | [Link](./test/hard/test_115_distinct_subsequences.rb) |
650650
| 126. Word Ladder II | [Link](https://leetcode.com/problems/word-ladder-ii/) | [Link](./lib/hard/126_word_ladder_ii.rb) | [Link](./test/hard/test_126_word_ladder_ii.rb) |
651651
| 233. Number of Digit One | [Link](https://leetcode.com/problems/number-of-digit-one/) | [Link](./lib/hard/233_number_of_digit_one.rb) | [Link](./test/hard/test_233_number_of_digit_one.rb) |
652+
| 239. Sliding Window Maximum | [Link](https://leetcode.com/problems/sliding-window-maximum/) | [Link](./lib/hard/239_sliding_window_maximum.rb) | [Link](./test/hard/test_239_sliding_window_maximum.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '7.7.9'
8+
s.version = '7.8.0'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/sliding-window-maximum/
4+
# @param {Integer[]} nums
5+
# @param {Integer} k
6+
# @return {Integer[]}
7+
def max_sliding_window(nums, k)
8+
result = ::Array.new(nums.size - k + 1)
9+
p = 0
10+
i = 0
11+
j = 0
12+
arr = []
13+
14+
while j < nums.size
15+
arr.pop while !arr.empty? && nums[j] > arr.last
16+
17+
arr << nums[j]
18+
size = j - i + 1
19+
20+
if size >= k
21+
result[p] = arr.first
22+
23+
arr.shift if arr.first == nums[i]
24+
25+
p += 1
26+
i += 1
27+
end
28+
29+
j += 1
30+
end
31+
32+
result
33+
end
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/hard/239_sliding_window_maximum'
5+
require 'minitest/autorun'
6+
7+
class SlidingWindowMaximumTest < ::Minitest::Test
8+
def test_default_one
9+
assert_equal(
10+
[3, 3, 5, 5, 6, 7],
11+
max_sliding_window(
12+
[1, 3, -1, -3, 5, 3, 6, 7],
13+
3
14+
)
15+
)
16+
end
17+
18+
def test_default_two
19+
assert_equal(
20+
[1],
21+
max_sliding_window(
22+
[1],
23+
1
24+
)
25+
)
26+
end
27+
end

0 commit comments

Comments
 (0)