Program to find number of increasing subsequences of size k in Python


Suppose we have a list of numbers called nums and also another value k, we have to find the number of subsequences of size k that are strictly increasing. If the answer is very large, mod it by 10^9 + 7.

So, if the input is like nums = [2, 3, 4, 1] k = 2, then the output will be 3, as we have the subsequences of size 2: [2, 3], [3, 4], [2, 4].

To solve this, we will follow these steps −

  • m := 10^9 + 7
  • dp := a list of size same as nums and fill with 1
  • iterate the following k times, do
    • for j in range size of dp - 1 to 0, decrease by 1, do
      • dp[j] := 0
      • for i in range 0 to j, do
        • if nums[i] < nums[j], then
          • dp[j] := dp[j] + dp[i]
  • return (sum of all elements in dp) mod m

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, nums, k):
      m = 10 ** 9 + 7
      dp = [1] * len(nums)
      for _ in range(k - 1):
         for j in range(len(dp) - 1, -1, -1):
            dp[j] = 0
            for i in range(j):
               if nums[i] < nums[j]:
                  dp[j] += dp[i]
      return sum(dp) % m
ob = Solution()
nums = [2, 3, 4, 1]
k = 2
print(ob.solve(nums, k))

Input

[2, 3, 4, 1], 2

Output

3

Updated on: 12-Dec-2020

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements