Skip to content

Commit 621834d

Browse files
author
Jeongwon Na
committed
solution: longest increasing subsequence
1 parent f3b689d commit 621834d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// time complexity: O(nlogn), n: nums.length (logn because of binary search)
2+
// space complexity: O(n), n: nums.length
3+
class Solution {
4+
public int lengthOfLIS(int[] nums) {
5+
ArrayList<Integer> incSeqList = new ArrayList<Integer>(); // dp
6+
incSeqList.add(nums[0]);
7+
8+
for (int num : nums) {
9+
if (num > incSeqList.get(incSeqList.size()-1)) {
10+
// add element to incSeqLit
11+
incSeqList.add(num);
12+
} else {
13+
int idx = Collections.binarySearch(incSeqList, num);
14+
if (idx < 0) { // idx returns -(insertedPos + 1)
15+
int insertedIdx = -(idx + 1);
16+
incSeqList.set(insertedIdx, num);
17+
}
18+
}
19+
}
20+
21+
return incSeqList.size();
22+
}
23+
}

0 commit comments

Comments
 (0)