|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1732. Find the Highest Altitude |
| 4 | +# https://leetcode.com/problems/find-the-highest-altitude |
| 5 | +# Easy |
| 6 | + |
| 7 | +=begin |
| 8 | +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. |
| 9 | +
|
| 10 | +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. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: gain = [-5,1,5,0,-7] |
| 14 | +Output: 1 |
| 15 | +Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: gain = [-4,-3,-2,-1,4,3,2] |
| 19 | +Output: 0 |
| 20 | +Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. |
| 21 | +
|
| 22 | +Constraints: |
| 23 | +n == gain.length |
| 24 | +1 <= n <= 100 |
| 25 | +-100 <= gain[i] <= 100 |
| 26 | +=end |
| 27 | + |
| 28 | +# @param {Integer[]} gain |
| 29 | +# @return {Integer} |
| 30 | +def largest_altitude(gain) |
| 31 | + prefix = gain.inject([]) { |acc, value| acc << acc.last.to_i + value.to_i } |
| 32 | + max_gain = prefix.max |
| 33 | + max_gain < 0 ? 0 : max_gain |
| 34 | +end |
| 35 | + |
| 36 | +# **************** # |
| 37 | +# TEST # |
| 38 | +# **************** # |
| 39 | + |
| 40 | +require "test/unit" |
| 41 | +class Test_largest_altitude < Test::Unit::TestCase |
| 42 | + def test_ |
| 43 | + assert_equal 1, largest_altitude([-5, 1, 5, 0, -7]) |
| 44 | + assert_equal 0, largest_altitude([-4, -3, -2, -1, 4, 3, 2]) |
| 45 | + end |
| 46 | +end |
0 commit comments