LeetCode - Easy - 1732. Find the Highest Altitude

古城微笑少年丶 2022-11-17 10:06 118阅读 0赞

Topic

  • Array

Description

https://leetcode.com/problems/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:

  1. Input: gain = [-5,1,5,0,-7]
  2. Output: 1
  3. Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.

Example 2:

  1. Input: gain = [-4,-3,-2,-1,4,3,2]
  2. Output: 0
  3. Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.

Constraints:

  • n == gain.length
  • 1 <= n <= 100
  • -100 <= gain[i] <= 100

Analysis

Submission

  1. public class FindTheHighestAltitude {
  2. public int largestAltitude(int[] gain) {
  3. int max = 0, sum = 0;
  4. for (int num : gain) {
  5. sum += num;
  6. if (sum > max)
  7. max = sum;
  8. }
  9. return max;
  10. }
  11. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. public class FindTheHighestAltitudeTest {
  4. @Test
  5. public void test() {
  6. FindTheHighestAltitude obj = new FindTheHighestAltitude();
  7. assertEquals(1, obj.largestAltitude(new int[] { -5, 1, 5, 0, -7}));
  8. assertEquals(0, obj.largestAltitude(new int[] { -4, -3, -2, -1, 4, 3, 2}));
  9. }
  10. }

发表评论

表情:
评论列表 (有 0 条评论,118人围观)

还没有评论,来说两句吧...

相关阅读