Created
March 29, 2017 21:01
-
-
Save DakotaLMartinez/817ae5cd432e8a5e0337b19b53e1892a to your computer and use it in GitHub Desktop.
This one is O(n) time complexity, but there's still a weird bug coming up in the test cases...
This file contains 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
def create_peaks(a) | |
peaks = [false] | |
(1..a.size - 2).each do |i| | |
if a[i] > a[i - 1] && a[i] > a[i + 1] | |
peaks << true | |
else | |
peaks << false | |
end | |
end | |
peaks | |
end | |
def next_peak(a) | |
n = a.size | |
peaks = create_peaks(a) | |
next_map = Array.new(n).fill(0) | |
next_map[n-1] = -1 | |
(a.size - 2).downto(-1).each do |i| | |
if peaks[i] | |
next_map[i] = i | |
else | |
next_map[i] = next_map[i+1] | |
end | |
end | |
next_map | |
end | |
def solution(a) | |
n = a.size | |
next_map = next_peak(a) | |
num_flags = 1 | |
max_flags = 0 | |
while (num_flags-1) * num_flags <= n | |
pos = 0 | |
num_placed = 0 | |
while pos < n && num_placed < num_flags | |
pos = next_map[pos] | |
break if pos == -1 | |
num_placed += 1 | |
pos += num_flags | |
end | |
max_flags = [max_flags, num_placed].max | |
num_flags += 1 | |
end | |
max_flags | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment