Skip to content

Commit

Permalink
09.30 : dp(가장 긴 증가하는 부분 수열 4)
Browse files Browse the repository at this point in the history
  • Loading branch information
luckylooky2 committed Sep 30, 2023
1 parent ef00657 commit f1f2838
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions baekjoon/14002.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 가장 긴 증가하는 부분 수열 4 : 동적 계획법
const input = require("fs")
.readFileSync("/dev/stdin")
.toString()
.trim()
.split("\n")
.map((v) => v.split(" ").map((v) => parseInt(v, 10)));
const [n] = input.shift();
const arr = input.shift();
const dp = new Array(n + 1).fill([]);
let maxArr = [];

for (let i = 1; i <= n; i++) {
const curr = arr[i - 1];
const lst = [];
let maxLen = -Infinity;
let index = 0;
for (let j = 0; j < i; j++) {
if (dp[j].length === 0) lst.push([curr]);
else if (dp[j][dp[j].length - 1] < curr) lst.push(dp[j].concat([curr]));
}
for (let i = 0; i < lst.length; i++) {
maxLen = Math.max(lst[i].length, maxLen);
if (maxLen === lst[i].length) index = i;
}
dp[i] = lst[index];
if (maxArr.length < dp[i].length) maxArr = dp[i];
}

console.log(maxArr.length);
console.log(maxArr.join(" "));

0 comments on commit f1f2838

Please sign in to comment.