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;
}
相关推荐
Queenie_Charlie12 分钟前
最长回文子串 V2(Manacher算法)
c++·算法·manacher算法
Evand J13 分钟前
【MATLAB复现RRT(快速随机树)算法】用于二维平面上的无人车路径规划与避障,含性能分析与可视化
算法·matlab·平面·无人车·rrt·避障
一招定胜负23 分钟前
机器学习+深度学习经典算法面试复习指南
深度学习·算法·机器学习
皮卡狮29 分钟前
高阶数据结构:AVL树
数据结构·算法
天若有情67337 分钟前
通用个性化推荐核心架构思路:从视频到电商的跨场景落地实践
人工智能·算法·架构·推流·个性化推荐·猜你喜欢
s090713637 分钟前
【声纳成像】基于滑动子孔径与加权拼接的条带式多子阵SAS连续成像(MATLAB仿真)
开发语言·算法·matlab·合成孔径声呐·后向投影算法·条带拼接
jay神38 分钟前
基于YOLOv8的钢材表面缺陷检测系统
人工智能·算法·yolo·目标检测·计算机视觉
Accerlator1 小时前
2026年3月21日刷题
算法
2401_891655811 小时前
此电脑网络位置异常的AD域排错指南的技术文章大纲
开发语言·python·算法
DLGXY1 小时前
STM32(二十七)——独立看门狗&窗口看门狗
stm32·嵌入式硬件·算法