https://leetcode.com/problems/longest-increasing-subsequence/
1. Problem
Given an unsorted array of integers, find the length of longest increasing subsequence.
2. Algorithm
I used dp solution with time complexity O(n^2).
Step 1. Iterate index i 0 to length of array. -> O(n)
Step 2. With index j find the longest length before d[i] iteratively, where nums[i] > nums[j]. -> O(n)
Step 3. After j loop, assign longest length + 1 to d[i] and compare d[i] to len value, save longer length. This step is included in loop i.
At the end, we can get the answer in value 'len'. Return len.
class Solution {
public int lengthOfLIS(int[] nums) {
int d[] = new int[nums.length];
int len = 0;
for(int i = 0; i < nums.length; i++) { // Step 1
if(d[i] == 0) {
int max = 0;
for (int j = 0; j < i; j++) // Step 2
if (nums[i] > nums[j]) max = Math.max(max, d[j]);
d[i] = max+1; // Step 3
len = Math.max(len,d[i]);
}
}
return len;
}
}
3. retrospective
Famous problem named LIS. I solved it with DP algorithm, but there is better solution with binary search(nlgn). If you find more faster solution, then I recommend check out the leetcode site.
'2. 알고리즘 공부 > JAVA 리트코드 풀이' 카테고리의 다른 글
[Leetcode] 221. Maximal Square (0) | 2019.06.20 |
---|---|
[LeetCode] 923. 3Sum With Multiplicity (0) | 2019.05.30 |
[Leetcode] 82. Remove Duplicates from Sorted List II (0) | 2019.05.01 |
[LeetCode] 236. Lowest Common Ancestor of a Binary Tree (0) | 2019.04.25 |
[Leetcode] 347. Top K Frequent Elements (0) | 2019.04.25 |