Skip to content

Commit 8a40a22

Browse files
Merge pull request #726 from jinoo0306/main
[조진우] 115차 라이브 코테 제출
2 parents fa90bcb + 7f07c71 commit 8a40a22

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const input = require("fs")
2+
.readFileSync(
3+
process.platform === "linux"
4+
? "/dev/stdin"
5+
: require("path").join(__dirname, "input.txt"),
6+
"utf8"
7+
)
8+
.trim()
9+
.split("\n")
10+
.map(Number);
11+
12+
function solution(input) {
13+
const arr = input.slice(1);
14+
let answer = 0;
15+
16+
function dfs(start, end) {
17+
if (start > end) return null;
18+
if (start === end) return arr[start];
19+
20+
let max = -Infinity;
21+
let maxIdx = -1;
22+
for (let i = start; i <= end; i++) {
23+
if (arr[i] > max) {
24+
max = arr[i];
25+
maxIdx = i;
26+
}
27+
}
28+
29+
const leftMax = dfs(start, maxIdx - 1);
30+
const rightMax = dfs(maxIdx + 1, end);
31+
32+
if (leftMax !== null) answer += max - leftMax;
33+
if (rightMax !== null) answer += max - rightMax;
34+
35+
return max;
36+
}
37+
38+
dfs(0, arr.length - 1);
39+
return answer;
40+
}
41+
42+
console.log(solution(input));
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const input = require("fs")
2+
.readFileSync(
3+
process.platform === "linux"
4+
? "/dev/stdin"
5+
: require("path").join(__dirname, "input.txt"),
6+
"utf8"
7+
)
8+
.trim()
9+
.split("\n");
10+
11+
function solution(input) {
12+
const N = +input[0];
13+
const A = input[1].split(" ").map(Number);
14+
const answer = new Array(N).fill(-1);
15+
const stack = [];
16+
17+
for (let i = N - 1; i >= 0; i--) {
18+
while (stack.length && stack[stack.length - 1] <= A[i]) stack.pop();
19+
20+
if (stack.length) answer[i] = stack[stack.length - 1];
21+
22+
stack.push(A[i]);
23+
}
24+
25+
return answer.join(" ");
26+
}
27+
28+
console.log(solution(input));

0 commit comments

Comments
 (0)