Skip to content

Commit 35da9f9

Browse files
Merge pull request #2 from rvguradiya/add-longest-increasing-subsequence
Add solution for finding the length of the longest increasing subsequ…
2 parents 22bf4e8 + b8c00f2 commit 35da9f9

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
This problem was asked by **Microsoft**.
2+
3+
Given an array of numbers, find the length of the longest increasing subsequence in the array. The subsequence does not necessarily have to be contiguous.
4+
5+
For example, given the array `[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]`, the longest increasing subsequence has length `6`: it is `0, 2, 6, 9, 11, 15`.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class Approach {
2+
3+
private static int[] dp;
4+
5+
public static int longestIncreasingSubsequence(int[] arr) {
6+
7+
int max = 0;
8+
for (int i = 0; i < arr.length; i++) {
9+
dp[i] = 1;
10+
for (int j = 0; j < i; j++) {
11+
if (arr[i] > arr[j]) {
12+
dp[i] = dp[i] > dp[j] + 1 ? dp[i] : dp[j] + 1;
13+
}
14+
}
15+
max = dp[i] > max ? dp[i] : max;
16+
}
17+
return max;
18+
}
19+
20+
public static void main(String[] args) {
21+
int[] arr = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
22+
dp = new int[arr.length];
23+
System.err.println(longestIncreasingSubsequence(arr));
24+
}
25+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function longestIncreasingSubsequence(nums) {
2+
n = nums.length;
3+
dp = Array(nums.length);
4+
max = 0;
5+
6+
// Build the DP array
7+
for (let i = 0; i < n; i++) {
8+
dp[i] = 1;
9+
for (let j = 0; j < i; j++) {
10+
if (nums[i] > nums[j]) {
11+
dp[i] = dp[i] > dp[j] + 1 ? dp[i] : dp[j] + 1;
12+
}
13+
}
14+
max = max > dp[i] ? max : dp[i];
15+
}
16+
17+
// The length of the longest increasing subsequence
18+
return max;
19+
}
20+
21+
// Example usage:
22+
let nums = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
23+
console.log(longestIncreasingSubsequence(nums));
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def length_of_lis(nums):
2+
if not nums:
3+
return 0
4+
5+
n = len(nums)
6+
dp = [1] * n # Initialize DP array with 1
7+
8+
# Build the DP array
9+
for i in range(1, n):
10+
for j in range(i):
11+
if nums[i] > nums[j]:
12+
dp[i] = max(dp[i], dp[j] + 1)
13+
14+
# The length of the longest increasing subsequence
15+
return max(dp)
16+
17+
# Example usage:
18+
nums = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
19+
print(length_of_lis(nums)) # Output: 6

0 commit comments

Comments
 (0)