Created
August 28, 2018 13:27
-
-
Save woodRock/1e7f0dea3b99b1fac62596525cf49d0b to your computer and use it in GitHub Desktop.
Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k. For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: 10 = max(10, 5, 2) 7 = max(5, 2, 7) 8 = max(2, 7, 8) 8 = max(7, 8, 7) Do this in O(n) time and O(k) space. You can …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
def maximum_subarray_values(k, arr) | |
max_vals = Array.new | |
arr.each do |i| | |
if max_vals.length == 0 || max_vals.length < k | |
max_vals << i | |
else | |
if i > max_vals.min | |
max_vals.pop(max_vals.min) | |
max_vals << i | |
end | |
end | |
end | |
return max_vals | |
end | |
arr = [10, 5, 2, 7, 8, 7] | |
puts maximum_subarray_values(3, arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment