Program to find maximum in generated array in Python

Given a number n, we need to generate an array A of length n + 1 using specific rules and find the maximum value in it.

Array Generation Rules

The array is built following these rules ?

  • 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

Example Walkthrough

For n = 5, let's see how the array is constructed ?

  • 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

The maximum value is 3.

Algorithm Steps

To solve this problem, we follow these steps ?

  • Initialize array A with indices from 0 to n

  • For each index i from 2 to n:

    • If i is even: A[i] = A[i//2]

    • If i is odd: A[i] = A[i//2] + A[i//2 + 1]

  • Return the maximum element in A

Implementation

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

n = 5
result = solve(n)
print(f"For n = {n}, maximum value is: {result}")

# Let's also print the generated array to see the pattern
def solve_with_array(n):
    A = [0] * (n + 1)
    A[0] = 0
    if n >= 1:
        A[1] = 1
    
    for i in range(2, n + 1):
        if i % 2 == 0:
            A[i] = A[i // 2]
        else:
            A[i] = A[i // 2] + A[(i // 2) + 1]
    
    return A, max(A)

array, maximum = solve_with_array(5)
print(f"Generated array: {array}")
print(f"Maximum value: {maximum}")
For n = 5, maximum value is: 3
Generated array: [0, 1, 1, 2, 1, 3]
Maximum value: 3

Testing with Different Values

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

# Test with different values
test_cases = [3, 5, 8, 10]
for n in test_cases:
    result = solve(n)
    print(f"n = {n}: maximum = {result}")
n = 3: maximum = 2
n = 5: maximum = 3
n = 8: maximum = 4
n = 10: maximum = 5

Time and Space Complexity

The algorithm has O(n) time complexity as we iterate through each index once. The space complexity is also O(n) for storing the array.

Conclusion

This problem demonstrates dynamic programming where each array element depends on previously computed values. The pattern creates a binary-tree-like structure where even indices copy parent values and odd indices sum adjacent parent values.

Updated on: 2026-03-25T20:25:13+05:30

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements