Skip to content

Commit 2db8bfd

Browse files
Create number_of_longest_increasing_subsequence.py
Implement function to count number of longest increasing subsequence
1 parent e2a78d4 commit 2db8bfd

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'''
2+
Leetcode Problem:673. Number of Longest Increasing Subsequence
3+
Link: https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
4+
5+
Given an integer array nums, return the number of longest increasing subsequences.
6+
Notice that the sequence has to be strictly increasing.
7+
8+
Example 1:
9+
10+
Input: nums = [1,3,5,4,7]
11+
Output: 2
12+
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
13+
Example 2:
14+
15+
Input: nums = [2,2,2,2,2]
16+
Output: 5
17+
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
18+
19+
20+
Constraints:
21+
22+
1 <= nums.length <= 2000
23+
-10**6 <= nums[i] <= 10**6
24+
The answer is guaranteed to fit inside a 32-bit integer.
25+
'''
26+
27+
28+
def findNumberOfLIS(nums):
29+
n = len(nums)
30+
if n == 0:
31+
return 0
32+
33+
length = [1] * n
34+
count = [1] * n
35+
36+
for i in range(n):
37+
for j in range(i):
38+
if nums[j] < nums[i]:
39+
if length[j] + 1 > length[i]:
40+
length[i] = length[j] + 1
41+
count[i] = count[j]
42+
elif length[j] + 1 == length[i]:
43+
count[i] += count[j]
44+
45+
max_len = max(length)
46+
return sum(c for l, c in zip(length, count) if l == max_len)
47+
48+
49+
# For testing...
50+
n=int(input())
51+
nums=list(map(int,input().split()))
52+
print(findNumberOfLIS(nums))

0 commit comments

Comments
 (0)