From aeb7ee9e5306029300d3c79ca747f8da1b436b8a Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Tue, 9 Mar 2021 19:19:45 -0800 Subject: [PATCH] add approach 2 --- .../arrays/find_the_highest_altitude.rb | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/arrays/find_the_highest_altitude.rb b/data_structures/arrays/find_the_highest_altitude.rb index f027a0c..73287b1 100644 --- a/data_structures/arrays/find_the_highest_altitude.rb +++ b/data_structures/arrays/find_the_highest_altitude.rb @@ -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