Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find length of longest increasing subsequence with at least k odd values in Python
Finding the length of the longest increasing subsequence with at least k odd values is a dynamic programming problem. We need to explore all possible increasing subsequences and track how many odd numbers each contains.
So, if the input is like nums = [12, 14, 16, 5, 7, 8] and k = 2, then the output will be 3, as the longest increasing subsequence with at least 2 odd values is [5, 7, 8].
Algorithm Approach
To solve this, we will follow these steps −
Initialize best := 0 to track the maximum length found
Define a recursive function dp() that takes parameters: i (current index), j (next index to check), odd (count of odd numbers), taken (current subsequence length)
If odd >= k, update best with maximum of current best and taken
If j reaches the end of nums, return from recursion
If nums[j] > nums[i], we can extend the subsequence: call dp(j, j + 1, odd + (nums[j] & 1), taken + 1)
Always try skipping the current element: dp(i, j + 1, odd, taken)
From main method, start dp for each possible starting position
Example
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
# Test the solution
ob = Solution()
nums = [12, 14, 16, 5, 7, 8]
k = 2
print("Input:", nums, "k =", k)
print("Output:", ob.solve(nums, k))
Input: [12, 14, 16, 5, 7, 8] k = 2 Output: 3
How It Works
The algorithm uses backtracking to explore all possible increasing subsequences. For each position, it decides whether to include the current element (if it maintains the increasing order) or skip it. The bitwise AND operation nums[j] & 1 efficiently checks if a number is odd − odd numbers have their least significant bit set to 1.
Additional Example
Let's test with another example to better understand the solution −
ob = Solution()
nums = [1, 3, 2, 4, 6, 5]
k = 3
print("Input:", nums, "k =", k)
print("Output:", ob.solve(nums, k))
# Another test case
nums = [2, 4, 6, 8]
k = 1
print("Input:", nums, "k =", k)
print("Output:", ob.solve(nums, k))
Input: [1, 3, 2, 4, 6, 5] k = 3 Output: 4 Input: [2, 4, 6, 8] k = 1 Output: 0
Conclusion
This recursive approach with backtracking explores all possible increasing subsequences and finds the longest one containing at least k odd numbers. The time complexity is exponential, but it correctly solves the problem by checking all valid combinations.
