Skip to content

Commit 1c07c4f

Browse files
committed
Solve LeetCode 75 prefix sum problems
1 parent b446121 commit 1c07c4f

File tree

4 files changed

+55
-3
lines changed

4 files changed

+55
-3
lines changed

LeetCode-75/.vscode/launch.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
// "skipFiles": [
1212
// "<node_internals>/**"
1313
// ],
14-
// "program": "${workspaceFolder}\\LeetCode-75\\17-1493.js"
14+
// "program": "${workspaceFolder}\\LeetCode-75\\19-724.js"
1515
// }
1616
]
1717
}

LeetCode-75/18-1732.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// https://leetcode.com/problems/find-the-highest-altitude/description/?envType=study-plan-v2&envId=leetcode-75
2+
3+
const largestAltitude = (gain: number[]): number => {
4+
let highest = 0,
5+
sum = 0;
6+
7+
// O(N) SOLUTION
8+
for (let val of gain) {
9+
sum += val;
10+
if (sum > highest) highest = sum;
11+
}
12+
13+
return highest;
14+
};

LeetCode-75/19-724.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// https://leetcode.com/problems/find-pivot-index/description/?envType=study-plan-v2&envId=leetcode-75
2+
3+
const pivotIndex = (nums: number[]): number => {
4+
// O(N) SOLUTION, BUT UNACCEPTED; IT DOESN'T WORK PROPERLY WITH POSITIVE/NEGATIVE VALUES
5+
// let i = 0,
6+
// j = nums.length - 1,
7+
// leftSum = 0,
8+
// rightSum = 0;
9+
10+
// while (i < j) {
11+
// const nextLeftSum = leftSum + nums[i];
12+
// const nextRightSum = rightSum + nums[j];
13+
14+
// if (nextLeftSum > nextRightSum) {
15+
// // if (Math.abs(nextLeftSum) > Math.abs(nextRightSum)) {
16+
// rightSum = nextRightSum;
17+
// j--;
18+
// } else {
19+
// leftSum = nextLeftSum;
20+
// i++;
21+
// }
22+
// }
23+
24+
// return rightSum === leftSum ? i : -1;
25+
26+
// O(N) SOLUTION
27+
let i = 1,
28+
leftSum = 0,
29+
rightSum = nums.reduce((acc, val) => acc + val, 0) - nums[0];
30+
31+
while (i < nums.length && leftSum !== rightSum) {
32+
leftSum += nums[i - 1];
33+
rightSum -= nums[i];
34+
i++;
35+
}
36+
37+
return leftSum === rightSum ? i - 1 : -1;
38+
};

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@
3030

3131
### Prefix Sum
3232

33-
- [ ] 18. Find the Highest Altitude
34-
- [ ] 19. Find Pivot Index
33+
- [X] 18. Find the Highest Altitude
34+
- [X] 19. Find Pivot Index
3535

3636
### Hash Map / Set
3737

0 commit comments

Comments
 (0)