I am trying to write an efficient 0(nlogn) algorithm for longest increasing subseuqnce:
def whereToInsert(a, k):
l, r = 0, len(a)-1
while l<=r:
m = l + (r-l)//2
if a[m]==k:
return m
elif a[m]>k:
r = m - 1
else:
l = m + 1
if l==len(a)-1:
return l+1
else:
return l
#print(whereToInsert([1,2,3,4,5,6,7,8,9], 0.5)) #This works fine
def lengthOfLISEfficient(nums):
lis = [nums[0]]
for x in nums[1:]:
t = whereToInsert(lis,x)
if t>=len(lis):
lis.append(0)
lis.insert(t, x)
return len(lis)
print(lengthOfLISEfficient([10,9,2,5,3,4]))
But the answer returned is 7 whereas the logest increasing subsequence 2 3 4 is of length 3.
The algorithm is described at the end in https://leetcode.com/problems/longest-increasing-subsequence/.
I am not getting why the answer is coming 7, my algorithm is following the correct logic.
Thanks for your help.