add approach 2

This commit is contained in:
Vitor Oliveira 2021-03-09 19:19:45 -08:00
parent adf94db012
commit aeb7ee9e53

View file

@ -18,6 +18,10 @@
# The highest is 1.
#
#
# Approach 1: Creating an additional array
#
# @param {Integer[]} gain
# @return {Integer}
def largest_altitude(gain)
@ -43,3 +47,29 @@ largest_altitude(gain)
gain = [-4, -3, -2, -1, 4, 3, 2]
largest_altitude(gain)
# Output: 0
#
# Approach 2: Without creating an additional array
#
# @param {Integer[]} gain
# @return {Integer}
def largest_altitude(gain)
max_alt = alt = 0
(0...gain.count).each do |i|
alt += gain[i]
max_alt = alt if max_alt < alt
end
max_alt
end
gain = [-5, 1, 5, 0, -7]
largest_altitude(gain)
# Output: 1
gain = [-4, -3, -2, -1, 4, 3, 2]
largest_altitude(gain)
# Output: 0