Skip to content

Commit b519e50

Browse files
committed
[leet] candy (greedy) (mid)
1 parent e7665ed commit b519e50

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

허현빈/7주차/260212-1.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} h
3+
* @return {number}
4+
*/
5+
var trap = function (h) {
6+
const n = h.length;
7+
if (n === 0) return 0;
8+
9+
const leftMax = new Array(n).fill(0);
10+
const rightMax = new Array(n).fill(0);
11+
12+
leftMax[0] = h[0];
13+
for (let i = 1; i < n; i++) {
14+
leftMax[i] = Math.max(leftMax[i - 1], h[i]);
15+
}
16+
17+
rightMax[n - 1] = h[n - 1];
18+
for (let i = n - 2; i >= 0; i--) {
19+
rightMax[i] = Math.max(rightMax[i + 1], h[i]);
20+
}
21+
22+
let totalWater = 0;
23+
for (let i = 0; i < n; i++) {
24+
totalWater += Math.min(leftMax[i], rightMax[i]) - h[i];
25+
}
26+
27+
return totalWater;
28+
};

허현빈/7주차/260212-2.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[]} ratings
3+
* @return {number}
4+
*/
5+
var candy = function (ratings) {
6+
const n = ratings.length;
7+
const ans = new Array(n).fill(1);
8+
9+
for (let i = 1; i < n; i++) {
10+
if (ratings[i] > ratings[i - 1]) {
11+
ans[i] = ans[i - 1] + 1;
12+
}
13+
}
14+
15+
for (let i = n - 2; i >= 0; i--) {
16+
if (ratings[i] > ratings[i + 1]) {
17+
ans[i] = Math.max(ans[i], ans[i + 1] + 1);
18+
}
19+
}
20+
21+
return ans.reduce((a, b) => a + b, 0);
22+
};

0 commit comments

Comments
 (0)