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;
}
相关推荐
დ旧言~1 分钟前
【高阶数据结构】图论
算法·深度优先·广度优先·宽度优先·推荐算法
时光の尘1 分钟前
C语言菜鸟入门·关键字·float以及double的用法
运维·服务器·c语言·开发语言·stm32·单片机·c
张彦峰ZYF6 分钟前
投资策略规划最优决策分析
分布式·算法·金融
-一杯为品-10 分钟前
【51单片机】程序实验5&6.独立按键-矩阵按键
c语言·笔记·学习·51单片机·硬件工程
The_Ticker21 分钟前
CFD平台如何接入实时行情源
java·大数据·数据库·人工智能·算法·区块链·软件工程
Lenyiin1 小时前
02.06、回文链表
数据结构·leetcode·链表
爪哇学长1 小时前
双指针算法详解:原理、应用场景及代码示例
java·数据结构·算法
爱摸鱼的孔乙己1 小时前
【数据结构】链表(leetcode)
c语言·数据结构·c++·链表·csdn
Dola_Pan1 小时前
C语言:数组转换指针的时机
c语言·开发语言·算法
繁依Fanyi1 小时前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse