99클럽 코테스터디
[99클럽 코테 스터디 29일차 TIL] Longest Increasing Subsequence
kittity
2024. 8. 19. 21:53
💡문제
https://leetcode.com/problems/longest-increasing-subsequence/description/
Given an integer array nums, return the length of the longest strictly increasing subsequence.
Example 1:
Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3] Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7] Output: 1
Constraints:
- 1 <= nums.length <= 2500
- 104 <= nums[i] <= 104
💡키워드
- 이분탐색
💡접근/해결 방법
✅ 풀이
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums:
return 0
# dp 배열을 nums와 같은 길이로 생성하고 모든 값을 1로 초기화
dp = [1] * len(nums)
# 모든 요소를 순회하며 부분 수열의 길이를 계산
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
# dp 배열에서 가장 큰 값이 가장 긴 증가하는 부분 수열의 길이
return max(dp)
728x90