LinkedIn Online Assessment Test
If you have a subsequence,
you can find the longest contiguous subarray with its sum<=limit
Example:
arr=[2,3,1,1,5], limit=7
(solution=4) because longest subarray=[2, 3, 1, 1]
arr=[1,2, 3, 6, 4, 3], limit=10
(solution=3) because longest subarray = [1, 2, 3]
I was also able to print the solution subaarray
I used a recursive call. For example 1:
[2]->[2,3]->[2,3,1]->[2,3,1,1]->[2,3,1,1,5]
[3]->[3,1]->[3,1,1]->[3,1,1,5]
[1]->[1,1]->[1,1,5]
[1]->[1,5]
[5]
arr=[1,2, 3, 6, 4, 3]
limit=10
n=len(arr)
maxi=0
elem=[]
def findk(start, end):
if end==n+1:
return
lis=arr[start:end]
x=sum(lis)
global maxi,elem,limit
if x<=limit:
maxi=max(maxi,len(lis))
if len(lis)==maxi:
elem=lis
findk(start,end+1)
for i in range(0,len(arr)):
findk(i,i+1)
print(maxi)
print(elem)
Complexity is O(n*((n+1)/2))