Skip to content

Commit c5524bf

Browse files
committed
Add solution for pivot index
1 parent f1bf57d commit c5524bf

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

Diff for: prefix-sum/pivot-index/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# 1732. Find the Highest Altitude
2+
3+
## Description
4+
See https://leetcode.com/problems/find-the-highest-altitude/description/
5+
6+
## Problem
7+
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`.
8+
9+
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.
10+
11+
## Example 1
12+
13+
```
14+
Input: gain = [-5,1,5,0,-7]
15+
Output: 1
16+
Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
17+
```
18+
19+
## Example 2
20+
21+
```
22+
Input: gain = [-4,-3,-2,-1,4,3,2]
23+
Output: 0
24+
Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
25+
```
26+
27+
## Constraints
28+
29+
```
30+
n == gain.length
31+
1 <= n <= 100
32+
-100 <= gain[i] <= 100
33+
```

Diff for: prefix-sum/pivot-index/pivot.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def index(nums: list[int]) -> int:
2+
left, right = 0, sum(nums)
3+
for idx, ele in enumerate(nums):
4+
right -= ele
5+
if left == right:
6+
return idx
7+
left += ele
8+
return -1

Diff for: prefix-sum/pivot-index/pivot_test.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from pivot import index
2+
3+
def test_example_1():
4+
nums = [1, 7, 3, 6, 5, 6]
5+
assert index(nums) == 3
6+
7+
def test_example_2():
8+
nums = [1, 2, 3]
9+
assert index(nums) == -1
10+
11+
def test_example_3():
12+
nums = [2, 1, -1]
13+
assert index(nums) == 0
14+
15+
def test_example_4():
16+
nums = [0, 0, 0, 0, 1]
17+
assert index(nums) == 4
18+
19+
def test_example_6():
20+
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
21+
assert index(nums) == -1

0 commit comments

Comments
 (0)