๐Ÿ”ฅ[99ํด๋Ÿฝ ์ฝ”ํ…Œ ์Šคํ„ฐ๋””] 29์ผ์ฐจ TIL - Longest Increasing Subsequence

HOONSSACยท2024๋…„ 8์›” 19์ผ
1

99Club Coding Test Study

๋ชฉ๋ก ๋ณด๊ธฐ
29/41
post-thumbnail

โณ๋ฌธ์ œ

Given an integer array nums, return the length of the largest strictly increaing subsequence.

๐Ÿšจ์ œํ•œ ์‚ฌํ•ญ

  • 1 <= nums.length <= 2500
  • $-10^4$ <= nums[i] <= $10^4$

๐Ÿ“ƒ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…์ถœ๋ ฅ ์˜ˆ #1

InputOutput
nums = [10,9,2,5,3,7,101,18]4

Explanation : The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

์ž…์ถœ๋ ฅ ์˜ˆ #2

InputOutput
nums = [0,1,0,3,2,3]4

์ž…์ถœ๋ ฅ ์˜ˆ #3

InputOutput
nums = [7,7,7,7,7,7,7]1

โœ๏ธํ’€์ด

์ด ๋ฌธ์ œ๋Š” ์™„์ „ ํƒ์ƒ‰์œผ๋กœ๋„ ํ’€ ์ˆ˜ ์žˆ์ง€๋งŒ,
Dynamic Programming ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ๋” ํšจ์œจ์ ์ด๋‹ค.

Dynamic Programming ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ฃผ์–ด์ง„ nums์˜ ๊ธธ์ด๋งŒํผ์˜ dp๋ฐฐ์—ด์„ ํ•˜๋‚˜ ๋งŒ๋“ค์–ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
์ด ๋ฌธ์ œ์—์„œ dp๋ฐฐ์—ด์˜ ์—ญํ• ์€ i๋ฒˆ์งธ ์ˆซ์ž๊ฐ€ ๋งˆ์ง€๋ง‰ ๋ฐฐ์—ด์˜ ์›์†Œ์ผ ๋•Œ, ๊ทธ ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ๊ธด ์˜ค๋ฆ„์ฐจ์ˆœ ์ˆ˜์—ด์˜ ๊ธธ์ด๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค.
๊ทธ๋Ÿฌ๋ฉด, ์ด์ „ ํƒ์ƒ‰์˜ ๊ฒฐ๊ณผ๋ฅผ ์ตœ๋Œ€ํ•œ ํ™œ์šฉํ•  ์ˆ˜๊ฐ€ ์žˆ๊ฒŒ ๋œ๋‹ค.

dp ๋ฐฐ์—ด ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™”

// dp ๋ฐฐ์—ด ์ƒ์„ฑ
int[] dp = new int[nums.length];

// dp ๋ฐฐ์—ด ์ดˆ๊ธฐํ™”
for (int i = 0; i < dp.length; i++) {
	dp[i] = 1;
}

์ฃผ์–ด์ง„ nums๋ฐฐ์—ด ๊ธธ์ด๋งŒํผ dp ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ด ์ฃผ๊ณ ,
๋ชจ๋“  ์›์†Œ๋ฅผ 1๋กœ ์ดˆ๊ธฐํ™” ํ•œ๋‹ค.

์˜ค๋ฆ„์ฐจ์ˆœ ์ˆœ์—ด์˜ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ

for (int i = 1; i < nums.length; i++) {
	for (int j = 0; j < i; j++) {
		if (nums[j] < nums[i]) {
			dp[i] = Math.max(dp[i], dp[j] + 1);
		}
	}
}

ํ˜„์žฌ ์œ„์น˜ i์—์„œ i๋ณด๋‹ค ์™ผ์ชฝ์— ์žˆ๋Š” ์›์†Œ๋“ค์˜ dp[i] ๊ฐ’๋“ค์„ ํ™•์ธ ํ›„,
nums[j] < nums[i]์ธ ๊ฒฝ์šฐ ์›์†Œ๊ฐ’๋“ค์„ ๋น„๊ตํ•˜๊ณ , dp๋ฐฐ์—ด์— ์—…๋ฐ์ดํŠธ๋ฅผ ํ•ด ์ค€๋‹ค.


๐Ÿ‘พ์ตœ์ข… ์ฝ”๋“œ

public static int lengthOfLIS(int[] nums) {
        int answer = 1;

         // dp ๋ฐฐ์—ด ์ƒ์„ฑ
        int[] dp = new int[nums.length];

        // dp ๋ฐฐ์—ด ์ดˆ๊ธฐํ™”
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
        }

        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }

        for (int i : dp) {
            answer = Math.max(answer, i);
        }


        return answer;
    }

๐Ÿ”— ๋ฌธ์ œ ๋งํฌ
๐Ÿ’ปRepository

profile
ํ›ˆ์‹น์˜ ๊ฐœ๋ฐœ์—ฌํ–‰

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2024๋…„ 8์›” 20์ผ

์–ด๋ ค์›Œ๋„ ํฌ๊ธฐํ•˜์ง€ ๋ง๊ณ  ์•„์ž์•„์ž

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ