Skip to content

Commit 4067e25

Browse files
committed
Longest Increasing Subsequence Solution
1 parent e6bd7eb commit 4067e25

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* ์ตœ์žฅ ์ฆ๊ฐ€ ๋ถ€๋ถ„ ์ˆ˜์—ด(Longest Increasing Subsequence, LIS)'์„ ๊ตฌํ•˜๊ธฐ
3+
* ๋ถ€๋ถ„ ์ˆ˜์—ด(Subsequence): ์›๋ž˜ ์ˆ˜์—ด์—์„œ ๋ช‡ ๊ฐœ์˜ ์›์†Œ๋ฅผ ๊ณจ๋ผ์„œ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ๋‚˜์—ดํ•œ ๊ฒƒ
4+
* ์ฆ๊ฐ€ ๋ถ€๋ถ„ ์ˆ˜์—ด(Increasing Subsequence): ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ์›์†Œ๋“ค์ด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ ๊ฒƒ
5+
*
6+
* ์ ‘๊ทผ๋ฐฉ๋ฒ•: ๋™์ ๊ณ„ํš๋ฒ•(DP) ๋˜๋Š” ์ด์ง„ํƒ์ƒ‰(Binary Search)
7+
* 1. DP๋ฅผ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•: ์‹œ๊ฐ„๋ณต์žก๋„ O(n^2)
8+
* 2. ์ด์ง„ํƒ์ƒ‰์„ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•: ์‹œ๊ฐ„๋ณต์žก๋„ O(n log n) โœ… follow-up ๊ณ ๋ ค
9+
*/
10+
11+
/** ๋™์ ๊ณ„ํš๋ฒ•(DP)์œผ๋กœ ์ ‘๊ทผ
12+
* @param {number[]} nums
13+
* @return {number}
14+
*/
15+
var lengthOfLIS = function (nums) {
16+
if (nums.length === 0) return 0;
17+
18+
// dp[i]๋Š” ์ธ๋ฑ์Šค i๊นŒ์ง€์˜ ๊ฐ€์žฅ ๊ธด ์ฆ๊ฐ€ ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ๊ธธ์ด
19+
const dp = Array(nums.length).fill(1);
20+
21+
// ๋ชจ๋“  ์œ„์น˜์— ๋Œ€ํ•ด ๊ฒ€์‚ฌ
22+
for (let i = 1; i < nums.length; i++) {
23+
// ํ˜„์žฌ ์œ„์น˜๋ณด๋‹ค ์ด์ „์˜ ๋ชจ๋“  ์œ„์น˜๋ฅผ ๊ฒ€์‚ฌ
24+
for (let j = 0; j < i; j++) {
25+
// ํ˜„์žฌ ๊ฐ’์ด ์ด์ „ ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด, ์ด์ „ ์œ„์น˜์˜ LIS์— ํ˜„์žฌ ๊ฐ’์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Œ
26+
if (nums[i] > nums[j]) {
27+
// ๊ธฐ์กด ๊ฐ’๊ณผ (์ด์ „ ์œ„์น˜์˜ LIS ๊ธธ์ด + 1) ์ค‘ ๋” ํฐ ๊ฐ’์„ ์„ ํƒ
28+
dp[i] = Math.max(dp[i], dp[j] + 1);
29+
}
30+
}
31+
}
32+
33+
// dp ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ๊ฐ’์ด LIS์˜ ๊ธธ์ด
34+
return Math.max(...dp);
35+
};
36+
37+
/** ์ด์ง„ํƒ์ƒ‰(Binary Search)์œผ๋กœ ์ ‘๊ทผ
38+
* @param {number[]} nums
39+
* @return {number}
40+
*/
41+
var lengthOfLIS = function (nums) {
42+
if (nums.length === 0) return 0;
43+
44+
// tails[i]๋Š” ๊ธธ์ด๊ฐ€ i+1์ธ ์ฆ๊ฐ€ ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ๋งˆ์ง€๋ง‰ ์›์†Œ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’
45+
const tails = [];
46+
47+
for (let num of nums) {
48+
// ์ด์ง„ ํƒ์ƒ‰์œผ๋กœ num์ด ๋“ค์–ด๊ฐˆ ์œ„์น˜ ์ฐพ๊ธฐ
49+
let left = 0;
50+
let right = tails.length;
51+
52+
while (left < right) {
53+
const mid = Math.floor((left + right) / 2);
54+
if (tails[mid] < num) {
55+
left = mid + 1;
56+
} else {
57+
right = mid;
58+
}
59+
}
60+
61+
// ์ฐพ์€ ์œ„์น˜์— num ์‚ฝ์ž… ๋˜๋Š” ๋Œ€์ฒด
62+
if (left === tails.length) {
63+
tails.push(num); // ์ƒˆ๋กœ์šด ์ตœ์žฅ ๊ธธ์ด ๋ฐœ๊ฒฌ
64+
} else {
65+
tails[left] = num; // ๊ธฐ์กด ๊ฐ’ ๊ฐฑ์‹ 
66+
}
67+
}
68+
69+
// tails ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ LIS์˜ ๊ธธ์ด
70+
return tails.length;
71+
};

0 commit comments

Comments
ย (0)