-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.sequence.lis.js
More file actions
67 lines (60 loc) · 1.64 KB
/
string.sequence.lis.js
File metadata and controls
67 lines (60 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* @title: Longest Increasing SubSequence
* @description: lis in string
* @author: Thorsten Kober
* @email: [email protected]
*/
function lis(arr) {
const result = [];
let max = 0;
for (let i = 0; i < arr.length; i++) {
result[i] = 1;
}
for (let i = 1; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
if (arr[i] > arr[j] && result[i] < result[j] + 1) {
result[i] = result[j] + 1;
max = Math.max(max, result[i]);
}
}
}
return max;
}
function lis2(arr, i, max) {
if (i === arr.length) return 0;
const excl = lis2(arr, i + 1, max);
let current = 0;
if (arr[i] > max) {
current = 1 + lis2(arr, i + 1, arr[i]);
}
return Math.max(current, excl);
}
// npx jest algorithms/string/string.sequence.lis.js
describe('lis tabulation', () => {
test('lis([3, 10, 2, 1, 20])', () => {
const nums = [3, 10, 2, 1, 20];
expect(lis(nums)).toEqual(3);
});
test('lis[50, 3, 10, 7, 40, 80])', () => {
const nums = [50, 3, 10, 7, 40, 80];
expect(lis(nums)).toEqual(4);
});
test('lis([10, 22, 9, 33, 21, 50, 41, 60, 12])', () => {
const nums = [10, 22, 9, 33, 21, 50, 41, 60, 12];
expect(lis(nums)).toEqual(5);
});
});
describe('lis recursion', () => {
test('lis([3, 10, 2, 1, 20])', () => {
const nums = [3, 10, 2, 1, 20];
expect(lis2(nums, 0, 0)).toEqual(3);
});
test('lis[50, 3, 10, 7, 40, 80])', () => {
const nums = [50, 3, 10, 7, 40, 80];
expect(lis2(nums, 0, 0)).toEqual(4);
});
test('lis([10, 22, 9, 33, 21, 50, 41, 60, 12])', () => {
const nums = [10, 22, 9, 33, 21, 50, 41, 60, 12];
expect(lis2(nums, 0, 0)).toEqual(5);
});
});