查找最长双调子序列的Python程序
给定一个包含 n 个正整数的数组 arr[0 … n-1],如果 arr[] 的子序列先递增,然后递减,则称为双调。编写一个函数数组为参数并返回最长双音子序列长度的函数。
一个按升序排序的序列被认为是双调的,降序部分为空。类似地,降序序列被认为是双调,增加的部分为空。
例子:
Input arr[] = {1, 11, 2, 10, 4, 5, 2, 1};
Output: 6 (A Longest Bitonic Subsequence of length 6 is 1, 2, 10, 4, 2, 1)
Input arr[] = {12, 11, 40, 5, 3, 1}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 12, 11, 5, 3, 1)
Input arr[] = {80, 60, 30, 40, 20, 10}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 80, 60, 30, 20, 10)
来源:微软面试题
解决方案
此问题是标准最长递增子序列 (LIS) 问题的变体。令输入数组为长度为 n 的 arr[]。我们需要使用 LIS 问题的动态规划解决方案来构造两个数组 lis[] 和 lds[]。 lis[i] 存储以 arr[i] 结尾的最长递增子序列的长度。 lds[i] 存储从 arr[i] 开始的最长递减子序列的长度。最后,我们需要返回 lis[i] + lds[i] – 1 的最大值,其中 i 从 0 到 n-1。
以下是上述动态规划解决方案的实现。
Python
# Dynamic Programming implementation of longest bitonic subsequence problem
"""
lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly creates two temporary arrays
lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1.
lis[i] ==> Longest Increasing subsequence ending with arr[i]
lds[i] ==> Longest decreasing subsequence starting with arr[i]
"""
def lbs(arr):
n = len(arr)
# allocate memory for LIS[] and initialize LIS values as 1
# for all indexes
lis = [1 for i in range(n+1)]
# Compute LIS values from left to right
for i in range(1 , n):
for j in range(0 , i):
if ((arr[i] > arr[j]) and (lis[i] < lis[j] +1)):
lis[i] = lis[j] + 1
# allocate memory for LDS and initialize LDS values for
# all indexes
lds = [1 for i in range(n+1)]
# Compute LDS values from right to left
for i in reversed(range(n-1)): #loop from n-2 downto 0
for j in reversed(range(i-1 ,n)): #loop from n-1 downto i-1
if(arr[i] > arr[j] and lds[i] < lds[j] + 1):
lds[i] = lds[j] + 1
# Return the maximum value of (lis[i] + lds[i] - 1)
maximum = lis[0] + lds[0] - 1
for i in range(1 , n):
maximum = max((lis[i] + lds[i]-1), maximum)
return maximum
# Driver program to test the above function
arr = [0 , 8 , 4, 12, 2, 10 , 6 , 14 , 1 , 9 , 5 , 13,
3, 11 , 7 , 15]
print "Length of LBS is",lbs(arr)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
输出:
Length of LBS is 7
时间复杂度:O(n^2)
辅助空间:O(n)
请参阅有关最长双音子序列的完整文章 | DP-15 了解更多详情!