상세 컨텐츠

본문 제목

1732. Find the Highest Altitude

LeetCode

by 10002s 2023. 11. 11. 17:44

본문

Find the Highest Altitude - LeetCode

 

자전거 타는 사람이 도로 여행 중입니다. 도로 여행은 서로 다른 고도에 있는 n + 1개의 지점으로 이루어져 있습니다. 자전거 타는 사람은 고도가 0인 지점 0에서 여행을 시작합니다.
길이 n인 정수 배열 gain이 주어지는데, 여기서 gain[i]는 지점 i와 i + 1 사이의 고도 변화입니다 (0 <= i < n). 지점의 가장 높은 고도를 반환하세요.

 

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.

 

문제 요약:

길이 n인 정수 배열 gain이 주어지며, 배열의 각 요소는 지점 i와 i + 1 사이의 고도 변화를 나타냅니다. 고도는 0에서 시작하여 여행 중 얻게 되는 고도의 누적입니다. 가장 높은 고도를 찾아서 반환하세요.

풀이과정 설명:
  1. 높이의 누적 값을 저장할 변수 currentAltitude를 초기화합니다. 이 변수는 각 지점에서의 고도를 나타냅니다.
  2. 배열 gain을 순회하면서 각 지점에서의 고도를 누적합니다.
  3. 높이의 누적 값 중 가장 큰 값을 찾아 반환합니다.
class Solution {
    public int largestAltitude(int[] gain) {
        int maxH = 0;
        int height = 0;

        for(int _h : gain){
            height += _h;

            maxH = Math.max(maxH, height);
        }
        return maxH;
    }
}

 

 

반응형

관련글 더보기