LeetCode //C - 1732. Find the Highest Altitude

1732. 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.

Example 2:

Input: gain = [-4,-3,-2,-1,4,3,2]
Output: 0
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

From: LeetCode

Link: 1732. Find the Highest Altitude


Solution:

Ideas:
  1. Initialize two integer variables: currentAltitude and highestAltitude. Set both of them to 0 initially.
  2. Iterate through the gain array. For each element in the array, add its value to currentAltitude.
  3. After updating currentAltitude, check if it's higher than highestAltitude. If it is, update highestAltitude with the value of currentAltitude.
  4. After the loop, highestAltitude will hold the maximum altitude reached, so return it.
Code:
c 复制代码
int largestAltitude(int* gain, int gainSize) {
    int highestAltitude = 0;
    int currentAltitude = 0;

    for (int i = 0; i < gainSize; ++i) {
        currentAltitude += gain[i];
        if (currentAltitude > highestAltitude) {
            highestAltitude = currentAltitude;
        }
    }

    return highestAltitude;
}
相关推荐
是main不是漫20 小时前
【数据结构--双向链表】从前有个节点,它想要两头讨好…
c语言·数据结构·链表
Frostnova丶20 小时前
【算法笔记】最短路径算法
笔记·算法·图论
小此方20 小时前
Re:Linux系统篇(二十一)进程篇·六:穿过底层看本质,深入理解底层进程切换与 O(1) 调度算法
linux·驱动开发·算法
小O的算法实验室20 小时前
2026年SEVC,层级分解协同演化算法+带有无人机的车辆路径路径规划
算法·无人机
吃好睡好便好20 小时前
用直接输入的方式创建矩阵
开发语言·人工智能·学习·线性代数·算法·matlab·矩阵
过期动态20 小时前
【RabbitMQ高级篇】生产者可靠性、MQ可靠性、消费者可靠性以及延迟队列的实现
java·数据结构·分布式·算法·rabbitmq·ruby
晚烛20 小时前
CANN 自定义算子开发:Ascend C 编程接口与算子实现完整指南
c语言·开发语言·人工智能·python
Byte Wizard20 小时前
自定义类型:结构体
c语言·开发语言
z2005093021 小时前
今日算法(二叉搜索树)
学习·leetcode
『昊纸』℃21 小时前
《C语言电子新-2026最新版》-编程语言与程序
数据结构·算法·程序设计·编程语言·软件开发