Program to find length of longest increasing subsequence with at least k odd values in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and another value k, we have to find the size of the longest increasing subsequence with at least k odd elements.

So, if the input is like nums = [12, 14, 16, 5, 7, 8] k = 2, then the output will be 3, as the longest increasing subsequence with at least 2 odd values is [5, 7, 8].

To solve this, we will follow these steps −

  • best := 0

  • Define a function dp() . This will take i, j, odd, taken

  • if odd >= k, then

    • best := maximum of best and taken

  • if j is same as size of nums , then

    • return

  • if nums[j] > nums[i], then

    • dp(j, j + 1, odd +(nums[j] AND 1) , taken + 1)

  • dp(i, j + 1, odd, taken)

  • From the main method do the following −

  • for i in range 0 to size of nums, do

    • dp(i, i + 1, nums[i] AND 1, 1)

  • return best

Example 

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
def solve(self, nums, k):
   best = 0
   def dp(i, j, odd, taken):
      nonlocal best
      if odd >= k:
         best = max(best, taken)
      if j == len(nums):
         return
      if nums[j] > nums[i]:
         dp(j, j + 1, odd + (nums[j] & 1), taken + 1)
      dp(i, j + 1, odd, taken)
   for i in range(len(nums)):
      dp(i, i + 1, nums[i] & 1, 1)
   return best
ob = Solution()
nums = [12, 14, 16, 5, 7, 8]
k = 2
print(ob.solve(nums, k))

Input

[12, 14, 16, 5, 7, 8], 2

Output

3
raja
Published on 22-Dec-2020 06:40:14
Advertisements