Skip to content

Create: 1299-replace-elements-with-greatest-element-on-right-side.rb #2247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions ruby/1299-replace-elements-with-greatest-element-on-right-side.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# @param {Integer[]} arr
# @return {Integer[]}

#naive/brute force approach: time = O(n^2), space = O(n)
def replace_elements(arr)
ans = []
(0...arr.length - 1).each do |idx|
ans << arr.slice(idx + 1, arr.length).max
end
ans << - 1
ans
end

#iterate backwards while keeping track of previous max: time = O(n), space = O(1)
def replace_elements(arr)
max_right = -1
(arr.length - 1).downto(0).each do |idx|
new_max = [max_right, arr[idx]].max
arr[idx] = max_right
max_right = new_max
end
arr
end