From 892c5d0064e547484e2191e941eb737aabf68b6c Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Tue, 9 Mar 2021 19:10:06 -0800 Subject: [PATCH] Add approach --- .../arrays/find_the_highest_altitude.rb | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 data_structures/arrays/find_the_highest_altitude.rb diff --git a/data_structures/arrays/find_the_highest_altitude.rb b/data_structures/arrays/find_the_highest_altitude.rb new file mode 100644 index 0000000..f027a0c --- /dev/null +++ b/data_structures/arrays/find_the_highest_altitude.rb @@ -0,0 +1,45 @@ +# Find the Highest Altitude + +# There is a biker going on a road trip. The road trip +# consists of n + 1 points at different altitudes. The +# biker starts his trip on point 0 with altitude equal 0. + +# You are given an integer array gain of length n where +# gain[i] is the net gain in altitude between points i​​​​​​ +# and i + 1 for all (0 <= i < n). + +# Return the highest altitude of a point. + +# Example 1: +# +# Input: gain = [-5,1,5,0,-7] +# Output: 1 +# Explanation: The altitudes are [0,-5,-4,1,1,-6]. +# The highest is 1. +# + +# @param {Integer[]} gain +# @return {Integer} +def largest_altitude(gain) + arr = [0] + points = gain.count + + # calculate altitude array + (1..points).each do |pointer| + sum = arr[pointer - 1] + gain[pointer - 1] + arr.push(sum) + end + + # find maximum altitude + max = 0 + arr.each { |i| max = i if max < i } + max +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