mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-13 08:01:03 +01:00
add approach 2
This commit is contained in:
parent
adf94db012
commit
aeb7ee9e53
1 changed files with 30 additions and 0 deletions
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue