- Related Questions & Answers
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest substring with character count of at least k in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Longest Increasing Subsequence in Python
- Longest Increasing Subsequence
- Maximum sum subsequence with at-least k distant elements in C++ program
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence of three strings in Python
- Java Program for Longest Increasing Subsequence
- Program to find out the length of longest palindromic subsequence using Python
- Find the longest subsequence of an array having LCM at most K in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

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))

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

3

Advertisements