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 gaini 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 <= gaini <= 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;
}
相关推荐
wjcroom6 分钟前
时空和电子7-泡力模型含罗量
人工智能·算法·机器学习
KaMeidebaby10 分钟前
卡梅德生物技术快报 | Fab 合成文库构建与抗体筛选实验流程及数据解析
人工智能·python·tcp/ip·算法·机器学习
金融小师妹14 分钟前
基于AI事件驱动模型与验证溢价框架的市场分析:从预期交易到事实验证,原油与黄金面临关键定价重构
大数据·人工智能·算法·均值算法·线性回归
xxwl58520 分钟前
工作室小测的部分记录
c++·学习·算法
程序员zgh23 分钟前
C++ 万能引用与完美转发
c语言·开发语言·c++·经验分享·学习
智者知已应修善业23 分钟前
【51单片机串口通信甲机四个按键模拟四位二进制值发送乙机以十进制显示2位数码管】2024-6-14
c++·经验分享·笔记·算法·51单片机
KobeSacre24 分钟前
划分为k个相等的子集
算法·leetcode·深度优先
不会就选b25 分钟前
算法日常・每日刷题--<二分查找>2
算法
郝学胜_神的一滴31 分钟前
完全二叉树与堆底层原理深度剖析 | 手写C++大顶堆实现
数据结构·算法
coding者在努力32 分钟前
【无标题】
算法