↓Skip to main content
  1. LeetCode/

LeetCode 1732: Find the Highest Altitude

·1 min· ·
LeetCode Easy Array Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-23

  • Submissions: Accepted (first try)

Approach
#

Point i sits at gain[0] + ... + gain[i - 1], a prefix sum (Prefix Sum). The starting altitude 0 counts too, so the answer is at least 0.

My Solution
#

class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        best = cur = 0
        for g in gain:
            cur += g
            best = max(best, cur)
        return best

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The start at 0 is an altitude too; if every gain is negative the answer is 0.

Interview Explanation
#

The altitudes are prefix sums of gain, so I accumulate and keep the maximum, counting the starting 0. Time O(n), space O(1).

Related

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1413 note: the start value plus every prefix sum must be at least 1, so it is max(1, 1 - minimum prefix sum)
LeetCode 1480: Running Sum of 1d Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1480 note: the definition of a prefix sum, adding each element to the previous running total
LeetCode 1991: Find the Middle Index in Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1991 note: compute the total, maintain the left sum while scanning, and get the right sum as total - left - nums[i]
LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original