Skip to content

Commit b5cc8eb

Browse files
committed
feat: Add LongestIncresingSubsequene solution with dp
1 parent 606cfa0 commit b5cc8eb

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.hyeonah.javalabs.algorithm.top50coding.dynamicprogramming;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* should run in O(n2) complexity
7+
* O(n2) > for 문 2개
8+
*
9+
* 1. 연속적으로 증가하는 것만 선택한다.
10+
* 2. 증가되고 있는 마지막 부분이 다음부분에 이용되어야 한다.
11+
* 3. 증가되고 있는 부분을 따로 저장할 것 (비교해서 max)
12+
*/
13+
public class LongestIncreasingSubsequence {
14+
public static void main(final String[] args) {
15+
final int[] nums = {1, 2, 3, 2, 5, 2, 6, 10, 4, 12};
16+
// final int[] nums2 = {9, 11, 2, 8, 4, 7, 88, 15};
17+
System.out.println(new LongestIncreasingSubsequence().solution(nums));
18+
// System.out.println(new LongestIncreasingSubsequence().solution(nums2));
19+
}
20+
21+
private int solution(final int[] nums) {
22+
if(nums == null || nums.length == 0) {
23+
return 0;
24+
}
25+
26+
final int[] dp = new int[nums.length];
27+
// 1로 초기화
28+
Arrays.fill(dp, 1);
29+
30+
int answer = 1;
31+
for (int i = 0; i < nums.length; i++) {
32+
for (int j = 0; j < i; j++) {
33+
if(nums[j] < nums[i]) {
34+
dp[i] = Math.max(dp[j] + 1, dp[i]);
35+
}
36+
}
37+
answer = Math.max(answer, dp[i]);
38+
}
39+
40+
return answer;
41+
}
42+
}

0 commit comments

Comments
 (0)