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;
}
相关推荐
A懿轩A1 小时前
C/C++ 数据结构与算法【数组】 数组详细解析【日常学习,考研必备】带图+详细代码
c语言·数据结构·c++·学习·考研·算法·数组
古希腊掌管学习的神1 小时前
[搜广推]王树森推荐系统——矩阵补充&最近邻查找
python·算法·机器学习·矩阵
云边有个稻草人1 小时前
【优选算法】—复写零(双指针算法)
笔记·算法·双指针算法
半盏茶香1 小时前
在21世纪的我用C语言探寻世界本质 ——编译和链接(编译环境和运行环境)
c语言·开发语言·c++·算法
忘梓.2 小时前
解锁动态规划的奥秘:从零到精通的创新思维解析(3)
算法·动态规划
字节高级特工2 小时前
【C++】深入剖析默认成员函数3:拷贝构造函数
c语言·c++
计算机学长大白3 小时前
C中设计不允许继承的类的实现方法是什么?
c语言·开发语言
tinker在coding4 小时前
Coding Caprice - Linked-List 1
算法·leetcode
XH华8 小时前
初识C语言之二维数组(下)
c语言·算法
南宫生9 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论