Value Equals Previous Two

 Coding Problem Keys 

 Value Equals Previous Two 

 Problem Statement 

An array of N integers is passed as the input. The program must find the combination of integers forming a sequence whose length is more than 4 which satisfies the below conditions.

    - The i-th index must satisfy arr[i] = arr[i-1] + arr[i-2].
    - The length of the sequence must be the maximum possible.
    - If there are more than one sequences satisfying the above two conditions, then print the sequence which contains the smaller value integers.

If there is no such combination of integers, then the program must print -1.

 Input Format 

The first line contains the value of N.
The second line contains the N integer values separated by a space.

 Output Format 

The first line contains the integer values in the sequence or -1.

 Boundary Condition(s) 

1 <= N
 <= 25

 Example Input/Output 1 

 Input 

9
4 2 7 5 3 8 10 11 19

 Output 

2 3 5 8

 Explanation 

2 3 5 8 and 3 8 11 19 are the two sequences having same length. But as 2 3 5 8 contains the smaller values, it is printed as the output.

 Example Input/Output 2 

 Input 

4
1 5 6 10

 Output 

-1

 Explanation 

Here the sequence 1 5 6 length is not 4. Hence -1 is printed.

 Max Execution Time Limit: 1000 millisecs 

 Solution 

 Programming Language: Python 3 Language 

n=int(input())
l1=list(map(int,input().split()))
l1.sort()
l2,l3=[],[]
for i in range(n-1):
    for j in range(i+1,n):
        l2.append(l1[i])
        l2.append(l1[j])
        t1=0
        t2=1
        for foo in range(j+1,n):
            if(l1[foo]==(l2[t1]+l2[t2])):
                l2.append(l1[foo])
                t1+=1
                t2+=1
        l3.append(l2)
        l2=[]
l4,l5=[],[]
for i in l3:
    l4.append(len(i))
maxi=max(l4)
if(maxi<4):
    print(-1)
    exit()
for i in l3:
    if len(i)==maxi:
        l5.append(sum(i))
for i in l3:
    if sum(i)==min(l5):
        print(*i)
        break

# Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Mango Distribution

Maximum Goods Transported

RAT CHEESE MAZE

Alphabetical Order Pattern

Left Right Top Bottom Sum

Iterate Base