-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNUMBER OF LONGEST INCREASING SUBSEQUENCE
53 lines (47 loc) · 1.43 KB
/
NUMBER OF LONGEST INCREASING SUBSEQUENCE
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
Number of Longest Increasing Subsequence
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[] lis = new int[n];
int[] fq = new int[n];
lis[0] = 1;
fq[0] = 1;
int lo = 1;
for (int i = 1; i < nums.length; i++) {
int mx = 0;
int c = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (lis[j] > mx) {
mx = lis[j];
c = fq[j];
} else if (lis[j] == mx) {
c += fq[j];
}
}
}
fq[i] = c;
lis[i] = mx + 1;
if (lo < lis[i]) {
lo = lis[i];
}
}
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (lis[i] == lo) {
count += fq[i];
}
}
return count;
}
}