C#
C# - Longest Increasing Subsequence
Dev_Jen
2025. 7. 13. 23:56
๐ 300. Longest Increasing Subsequence
๐น ๋ฌธ์ ์ค๋ช
์ ์ ๋ฐฐ์ด nums๊ฐ ์ฃผ์ด์ง ๋,
๋ฐฐ์ด์์ ์ค๋ฆ์ฐจ์์ผ๋ก ์ฆ๊ฐํ๋ ๊ฐ์ฅ ๊ธด ๋ถ๋ถ ์์ด์ ๊ธธ์ด๋ฅผ ๊ตฌํ๋ผ.
- ๋ถ๋ถ ์์ด(subsequence):(์ฐ์๋ ๊ฐ์ผ ํ์๋ ์์)
- ์๋ ๋ฐฐ์ด์์ ์์๋ฅผ ์ ์งํ๋ฉด์ ์ผ๋ถ ์์๋ฅผ ๊ฑด๋๋ฐ์ด ์ ํํ ์ ์์
๐ธ ์์
Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]
Output: 4
์ค๋ช
: ๊ฐ์ฅ ๊ธด ์ค๋ฆ์ฐจ์ ๋ถ๋ถ ์์ด์ [2, 3, 7, 101] ์ด๋ฏ๋ก ๊ธธ์ด๋
๐น ์กฐ๊ฑด
- 1 <= nums.length <= 2500
- 10โด <= nums[i] <= 10โด
๐ฏ ๋ชฉํ
๐ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๊ธธ๊ฒ ์ค๋ฆ์ฐจ์์ผ๋ก ์ฆ๊ฐํ๋ ๋ถ๋ถ ์์ด์ ์ฐพ์์
๊ทธ ๊ธธ์ด๋ฅผ ๋ฐํํ๋ ํจ์๋ฅผ ์์ฑํ๋ ๊ฒ์ด ๋ชฉํ์ผ.
โ ์์ 2
Input: nums = [0, 1, 0, 3, 2, 3]
Output: 4
์ค๋ช
: [0, 1, 2, 3] ์ด ๊ฐ์ฅ ๊ธธ๋ค
๐ง ํต์ฌ ๊ฐ๋
์ด ๋ฌธ์ ๋ ์ ํ์ ์ธ ๋์ ๊ณํ๋ฒ (DP) ๋๋ ์ด์ง ํ์์ ์ด์ฉํ ์ต์ ํ ๋ฌธ์ ์ผ.
- ๊ธฐ๋ณธ DP ํ์ด: O(n²)
- ์ด์ง ํ์ ์ต์ ํ: O(n log n)
using System;
public class Program
{
public static void Main()
{
int[] nums = new int[] { 10, 9, 2, 5, 3, 7, 101, 18 };
Console.WriteLine("Input Array: " + string.Join(", ", nums));
int result = FindLengthOfLIS(nums);
Console.WriteLine("Longest Increasing Subsequence Length: " + result);
}
public static int FindLengthOfLIS(int[] nums)
{
int n = nums.Length;
if (n == 0) return 0;
int[] dp = new int[n];
for (int i = 0; i < n; i++)
dp[i] = 1; // ์ต์ ์๊ธฐ ์์
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (nums[j] < nums[i])
{
dp[i] = Math.Max(dp[i], dp[j] + 1);
}
}
}
int maxLength = 0;
for (int i = 0; i < n; i++)
maxLength = Math.Max(maxLength, dp[i]);
return maxLength;
}
}