본문 바로가기

Java/Java 알고리즘 LeetCode

[LeetCode- Ch8. 동적계획법] 4. 가장 긴 증가하는 서브시퀀스

반응형

https://leetcode.com/problems/longest-increasing-subsequence/

 

Longest Increasing Subsequence - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

참고 자료

https://and-some.tistory.com/643

 

[Ch.10 - DP] 03. 최대 부분 증가수열 [+LIS]

3. 최대 부분 증가수열 설명 N개의 자연수로 이루어진 수열이 주어졌을 때, 그 중에서 가장 길게 증가하는(작은 수에서 큰 수로) 원소들의 집합을 찾는 프로그램을 작성하라. 예를 들어, 원소가 2,

and-some.tistory.com

 


1. dp[i] : i의 위치에서 가장 긴 증가하는 서브시퀀스

2. i이전의 정수값과 비교해가면서 제일 큰 위치에서 정수값이 더 크면 +1한 값을 넣는다. 

 

class Solution {
    public int lengthOfLIS(int[] arr) {
        //dy[i] : 수열에서 i번째 숫자를 마지막으로 하는 최대 증가 수열의 길이
        int n=arr.length;
        int[] dp = new int[n];
        //[10,9,2,5,3,7,101,18]
        Arrays.fill(dp, 1);
        
        //(i 이전의 최대 증가 수열의 길이)와 (만약 해당 위치의 정수값보다
        //정수값이 더 크면, 자신의 최대 증가 수열의 길이+1)과 비교
        for(int i=0;i<n;i++){
            for(int j=0;j<=i;j++){
                //1>0 -> dp[1]= Math.max(0, dp[0]+1);
                if(arr[i]>arr[j]) 
                    dp[i]=Math.max(dp[i], dp[j]+1);
            }
        }
        int answer=Integer.MIN_VALUE;
        for(int x: dp) {
            System.out.print(x+" ");
            answer=Math.max(x,answer);
        }
        return answer;
    }
}
반응형