Sub array 左子数组中所有元素的最大较小值
我正在解决使用动态规划和Sub array 左子数组中所有元素的最大较小值,sub-array,Sub Array,我正在解决使用动态规划和O(n^2)的问题,根据以下伪代码(基本上,我们使用自下而上的方法来获得给定数组的所有I的在索引I处结束的最大递增子序列的长度): 虽然我对上述问题采用了不同的方法,但我想到了对上述方法的修改,从而导致了另一个问题,我无法想象我是否能在比O(n^2)时间更好的时间内解决该问题 我想如果我能知道[0,len(nums)-1]中所有I的最大元素小于nums[I],那么我可以这样做(我不确定这种方法是否完全正确) 现在,我的问题不是上述解决上述问题的方法是否正确,而是如何在O(
O(n^2)
的问题,根据以下伪代码(基本上,我们使用自下而上的方法来获得给定数组的所有I的在索引I
处结束的最大递增子序列的长度):
虽然我对上述问题采用了不同的方法,但我想到了对上述方法的修改,从而导致了另一个问题,我无法想象我是否能在比O(n^2)
时间更好的时间内解决该问题
我想如果我能知道[0,len(nums)-1]
中所有I的最大元素小于nums[I]
,那么我可以这样做(我不确定这种方法是否完全正确)
现在,我的问题不是上述解决上述问题的方法是否正确,而是如何在O(n^2)
内使数组向左
。如果我能在少于O(n^2)
的时间内得到左
,那么检查上述方法是否有效将是值得的(尽管这不是在这里问这个问题的目的,我添加了它以显示我是如何遇到上述问题的)。是否可以在小于O(n^2)
的时间内构建left
。为清晰起见,我在下面为左
添加了更多的输入和输出(在下面的示例中,我将在左
中显示所需的索引):
#nums is sequence of numbers like [10,9,2,5,3,7,101,18]
dp=[1]*len(nums) #dp[i] is length of longest increasing sub-sequence ending at element nums[i]
for i in range(len(lst)):
for j in range(i):
if nums[i]>nums[j]:
dp[i]=max(dp[i], dp[j]+)
#max(dp) will give the length of Longest Increasing Sub-sequence
#nums is sequence of numbers like [10,9,2,5,3,7,101,18]
left=[]
#Suppose left is a list of length len(nums) such that left[i] will give largest element smaller than nums[i] in left sub-array for nums (excluding i)
#i.e. for above nums array, left = [-1,-1,-1,2,2,5,10,10] #I am showing values here for clarity but I can as well store index of largest element smaller than nums[i] for quick access
#No element is left to 10 so left[0]=-1
#No element left to 9 is smaller than 9 so left[1]=-1
#No element left to 2 is smaller than 2 so left[2]=-1
#In array left to 5, 2 is than largest element smaller than 5 so, left[3]=2, and so on
#Now
dp=[1]*len(lst) #dp[i] is length of longest increasing sub-sequence ending at element nums[i]
for i in range(len(lst)):
if left[i]!=-1:
dp[i]=max(dp[i], dp[left[i]]+1) #Assuming I am storing indices in array left
Input: [10,9,2,5,3,7,101,18]
Output: [-1,-1,-1,2,2,3,0,0]
Input: [10,9,8,7,6,8]
Output: [-1,-1,-1,-1,-1,3] #largest element smaller than 8 in left sub-array of 8 is 7 whose index is 3
Input: [0,1,2,3,4,5,6]
Output: [-1,0,1,2,3,4,5] #no element in left sub-array of element 0, so left[0]=-1