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;
}
相关推荐
Erik_LinX24 分钟前
算法日记36:leetcode095最长公共子序列(线性DP)
算法
2301_7665360525 分钟前
刷leetcode hot100--动态规划3.11
算法·leetcode·动态规划
VT.馒头26 分钟前
【力扣】2629. 复合函数——函数组合
前端·javascript·算法·leetcode
DOMINICHZL36 分钟前
卡尔曼滤波算法从理论到实践:在STM32中的嵌入式实现
stm32·嵌入式硬件·算法
CodeJourney.1 小时前
光储直流微电网:能源转型的关键力量
数据库·人工智能·算法·能源
GUOYUGRA1 小时前
高纯氢能源在线监测分析系统组成和作用
人工智能·算法·机器学习
是星辰吖~1 小时前
C语言_数据结构_队列
c语言·数据结构
Chenyu_3101 小时前
05.基于 TCP 的远程计算器:从协议设计到高并发实现
linux·网络·c++·vscode·网络协议·tcp/ip·算法
论迹2 小时前
【二分算法】-- 三种二分模板总结
java·开发语言·算法·leetcode
衡玖2 小时前
c语言闯算法--排序
c语言·数据结构·算法