Get Maximum in Generated Array - Problem

You are given an integer n and need to generate a special array following specific rules, then find the maximum value in it.

The array nums of length n + 1 is generated using these rules:

  • nums[0] = 0 (base case)
  • nums[1] = 1 (base case)
  • For even indices: nums[2 * i] = nums[i] when 2 ≤ 2 * i ≤ n
  • For odd indices: nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 ≤ 2 * i + 1 ≤ n

Goal: Return the maximum integer in the generated array.

Example: For n = 7, we generate: [0, 1, 1, 2, 2, 3, 3, 4] and return 4.

Input & Output

example_1.py — Basic Case
$ Input: n = 7
Output: 4
💡 Note: Generated array: [0,1,1,2,2,3,3,4]. nums[2]=nums[1]=1, nums[3]=nums[1]+nums[2]=2, nums[4]=nums[2]=1, nums[5]=nums[2]+nums[3]=3, nums[6]=nums[3]=2, nums[7]=nums[3]+nums[4]=4. Maximum is 4.
example_2.py — Small Case
$ Input: n = 2
Output: 1
💡 Note: Generated array: [0,1,1]. We have nums[0]=0, nums[1]=1, nums[2]=nums[1]=1. Maximum is 1.
example_3.py — Edge Case
$ Input: n = 0
Output: 0
💡 Note: Generated array: [0]. Only nums[0]=0 exists, so maximum is 0.

Constraints

  • 0 ≤ n ≤ 100
  • The generated array will have exactly n + 1 elements
  • All values in the array will be non-negative integers

Visualization

Tap to expand
Array Generation Tree Pattern (n=7)0i=01i=11i=2even: nums[1]2i=3odd: 1+12i=4even: nums[2]3i=5odd: 1+23i=6even: nums[3]4i=7odd: 2+2MAXResult: 4Final Array: [0, 1, 1, 2, 2, 3, 3, 4]Maximum Value Found: 4
Understanding the Visualization
1
Root Generation
Start with nums[0]=0 and nums[1]=1 as the foundation
2
Even Index Rule
For even indices like 2,4,6: copy value from nums[i/2]
3
Odd Index Rule
For odd indices like 3,5,7: sum nums[i//2] + nums[i//2+1]
4
Maximum Discovery
Scan completed array to find the largest generated value
Key Takeaway
🎯 Key Insight: This problem is pure simulation - no complex algorithms needed! Just follow the rules step by step to build the array, then find the maximum. The pattern creates a binary tree-like structure where values propagate down through specific mathematical relationships.
Asked in
Amazon 25 Google 20 Microsoft 15 Meta 12
31.5K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen