Skip to content

Commit 993ff07

Browse files
committed
solve(w06): 300. Longest Increasing Subsequence
1 parent 237811b commit 993ff07

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# https://leetcode.com/problems/longest-increasing-subsequence/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def lengthOfLIS_dp(self, nums: List[int]) -> int:
7+
"""
8+
[Complexity]
9+
- TC: O(n^2)
10+
- SC: O(n)
11+
12+
[Approach]
13+
dp[i] = nums[i]๊ฐ€ ํฌํ•จ๋˜๋Š” LIS์˜ ์ตœ๋Œ€ ๊ธธ์ด
14+
"""
15+
n = len(nums)
16+
dp = [1] * n
17+
18+
for i in range(n):
19+
for j in range(i):
20+
if nums[j] < nums[i]:
21+
dp[i] = max(dp[i], dp[j] + 1)
22+
23+
return max(dp)
24+
25+
def lengthOfLIS(self, nums: List[int]) -> int:
26+
"""
27+
[Complexity]
28+
- TC: O(nlogn) (w. binary search)
29+
- SC: O(n)
30+
31+
[Approach]
32+
ref: https://leetcode.com/problems/longest-increasing-subsequence/solutions/1326308/c-python-dp-binary-search-bit-segment-tree-solutions-picture-explain-o-nlogn
33+
nums๋ฅผ ์ˆœ์ฐจ์ ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉฐ LIS๋ฅผ ๋ชจ์€๋‹ค. ์ด๋•Œ,
34+
- ํ˜„์žฌ ๋ณด๊ณ  ์žˆ๋Š” ์›์†Œ n์ด LIS์˜ ๋งˆ์ง€๋ง‰ ์›์†Œ ์ดํ•˜๋ผ๋ฉด: LIS์˜ ์›์†Œ ์ค‘ (1) n ์ด์ƒ์ด๋ฉด์„œ (2) ์ตœ์†Ÿ๊ฐ’์˜ ์œ„์น˜์— n ๋ฎ์–ด์“ฐ๊ธฐ
35+
- ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ๋ผ๋ฉด: LIS์˜ ๋งจ ๋์— num append
36+
ํ•œ๋‹ค.
37+
LIS๋Š” ์ •๋ ฌ๋˜์–ด ์žˆ์„ ๊ฒƒ์ด๋ฏ€๋กœ binary search๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋ ‡๊ฒŒ ๊ตฌ์„ฑํ•œ LIS์˜ ๊ธธ์ด๊ฐ€ ์ตœ๋Œ€ ๊ธธ์ด์ด๋‹ค.
38+
"""
39+
40+
def find_leftmost_idx(lis, n):
41+
lo, hi = 0, len(lis) - 1
42+
43+
while lo < hi:
44+
mid = lo + (hi - lo) // 2
45+
if lis[mid] < n: # -- ์•„์˜ˆ ์ œ์™ธํ•˜๋Š” ๊ฒฝ์šฐ: n ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ
46+
lo = mid + 1
47+
else:
48+
hi = mid
49+
50+
return lo
51+
52+
lis = []
53+
54+
for n in nums:
55+
# ํ˜„์žฌ ๋ณด๊ณ  ์žˆ๋Š” n์ด LIS์˜ ๋งˆ์ง€๋ง‰ ์›์†Œ ์ดํ•˜๋ผ๋ฉด
56+
if lis and n <= lis[-1]:
57+
lis[find_leftmost_idx(lis, n)] = n
58+
# ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ๋ผ๋ฉด
59+
else:
60+
lis.append(n)
61+
62+
return len(lis)

0 commit comments

Comments
ย (0)