Program to find maximum in generated array in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to generate an array A of length n + 1 in the following way −

  • A[0] = 0

  • A[1] = 1

  • A[2 * i] = A[i] if 2 <= 2 * i <= n

  • A[2 * i + 1] = A[i] + A[i + 1] if 2 <= 2 * i + 1 <= n

Finally we have to find the maximum number in the array nums.

So, if the input is like n = 5, then the output will be 3 because

  • A[0] = 0

  • A[1] = 1

  • A[2] = A[1] = 1

  • A[3] = A[1] + A[2] = 1 + 1 = 2

  • A[4] = A[2]= 1

  • A[5] = A[2] + A[3] = 1 + 2 = 3

  • A[6] = A[3] = 2

So the maximum is 3

To solve this, we will follow these steps −

  • A := a new list from 0 to n

  • for each element i in A, do

    • if i is same as 0 or i is same as 1, then

      • go to next iteration

    • otherwise when i is even, then

      • A[i] := A[integer of i/2]

    • otherwise,

      • A[i] := A[integer of i/2] + A[(integer of i/2) + 1]

  • return maximum element of A

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(n):
   A = list(range(0,n+1))
   for i in A:
      if i == 0 or i == 1:
         continue
      elif i%2 == 0:
         A[i] = A[i//2]
      else:
         A[i] = A[i//2] + A[(i//2) + 1]
   return max(A)

n = 5
print(solve(n))

Input

5

Output

3
raja
Updated on 17-May-2021 13:11:48

Advertisements