5 Best Ways to Find Length of Longest Increasing Subsequence With At Least K Odd Values in Python

Rate this post

πŸ’‘ Problem Formulation: The task is to write a Python program that finds the length of the longest increasing subsequence from a list of integers which includes at least k odd values. For example, given the input [2, 3, 5, 7, 11, 8, 10] with k = 3, the desired output would be 5, corresponding to the subsequence [2, 3, 5, 7, 8].

Method 1: Dynamic Programming

Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems. For finding the longest increasing subsequence with at least k odd values, we use a two-dimensional DP array. One dimension tracks the length of the sequence while the other tracks the number of odd values.

Here’s an example:

def longest_increasing_subsequence_k_odds(arr, k):
    n = len(arr)
    # DP initialization
    dp = [[[0, 0] for _ in range(k+1)] for _ in range(n+1)]
    for i in range(1, n+1):
        for o in range(k+1):
            # Copy previous values
            dp[i][o] = dp[i-1][o].copy()
            # Skip the current element
            if o > 0 and arr[i-1] % 2 == 1:
                # Check if we can form a longer increasing subsequence
                for j in range(i):  # Trace previous elements
                    if arr[i-1] > arr[j-1] and dp[i][o][0]  arr[j-1] and dp[i][o][0] < dp[j][o][0] + 1:
                        dp[i][o] = [dp[j][o][0] + 1, dp[j][o][1]]
    # Find the maximum length with at least k odd values
    max_length = 0
    for i in range(n+1):
        for o in range(k, k+1):
            max_length = max(max_length, dp[i][o][0])
    return max_length

# Example usage:
print(longest_increasing_subsequence_k_odds([2, 3, 5, 7, 11, 8, 10], 3))

The output of this code snippet will be:


This dynamic programming solution sets up a table to record the longest increasing subsequence with different counts of odd values, and then iterates over the input array while updating the table accordingly. The result is the maximum length amongst all subsequences with at least k odd values.

Method 2: Recursive Approach with Memoization

The recursive approach breaks down the problem into smaller instances using a top-down approach, while memoization is used to store already calculated results to avoid recomputation. This method divides the problem into checking each element and deciding whether to include it or not while keeping track of the number of odd elements.

Here’s an example:

 from functools import lru_cachedef lon