Get Maximum in Generated Array - Problem

You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:

  • nums[0] = 0
  • nums[1] = 1
  • nums[2 * i] = nums[i] when 2 <= 2 * i <= n
  • nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n

Return the maximum integer in the array nums.

Input & Output

Example 1 — Basic Case
$ Input: n = 7
Output: 3
💡 Note: nums = [0,1,1,2,1,3,2,3]. Generated by rules: 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]=3. Maximum is 3.
Example 2 — Small Input
$ Input: n = 2
Output: 1
💡 Note: nums = [0,1,1]. nums[2] = nums[1] = 1. Maximum is 1.
Example 3 — Edge Case
$ Input: n = 0
Output: 0
💡 Note: nums = [0]. Only element is 0, so maximum is 0.

Constraints

  • 0 ≤ n ≤ 100

Visualization

Tap to expand
Get Maximum in Generated Array INPUT n = 7 Array length: n+1 = 8 Initial Array Structure: ? 0 ? 1 ? 2 ? 3 ? 4 ? 5 ? 6 Generation Rules: nums[0] = 0 nums[1] = 1 nums[2*i] = nums[i] nums[2*i+1] = nums[i] + nums[i+1] ALGORITHM STEPS 1 Initialize Base nums[0]=0, nums[1]=1, max=1 2 Loop i: 1 to n/2 Generate elements using rules 3 Apply Rules Even: copy, Odd: sum 4 Track Maximum Update max after each step Generation Trace: i=1: nums[2]=nums[1]=1 nums[3]=nums[1]+nums[2]=2 i=2: nums[4]=nums[2]=1 nums[5]=nums[2]+nums[3]=3 i=3: nums[6]=nums[3]=2 nums[7]=nums[3]+nums[4]=3 max = 3 (found at i=2) FINAL RESULT Generated Array nums[]: 0 0 1 1 1 2 2 3 1 4 3 5 2 6 3 7 Output: 3 Maximum value found: 3 at indices 5 and 7 Complete Array: [0,1,1,2,1,3,2,3] Status: OK Key Insight: The array follows a pattern similar to the Stern-Brocot sequence. Even indices copy from half their index, while odd indices sum two consecutive elements. By tracking maximum during generation, we achieve O(n) time complexity and O(n) space complexity - no need for a separate max-finding pass! TutorialsPoint - Get Maximum in Generated Array | Track Maximum While Generating
Asked in
Amazon 25 Microsoft 20
28.0K Views
Medium Frequency
~10 min Avg. Time
850 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