#1646
Get Maximum in Generated Array
EasyArraySimulationArraySimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution builds the array in a single pass while calculating the maximum value on-the-fly. This approach reduces unnecessary iterations and leverages the properties of the generated array.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array nums of length n + 1.
- 2Step 2: Set nums[0] = 0 and nums[1] = 1.
- 3Step 3: For each i from 1 to n // 2, fill nums[2 * i] and nums[2 * i + 1] as specified, while keeping track of the maximum value encountered.
solution.py14 lines
1# Full working Python code
2
3def getMaximumGenerated(n):
4 if n == 0:
5 return 0
6 nums = [0] * (n + 1)
7 nums[1] = 1
8 max_value = 1
9 for i in range(1, (n // 2) + 1):
10 nums[2 * i] = nums[i]
11 if 2 * i + 1 <= n:
12 nums[2 * i + 1] = nums[i] + nums[i + 1]
13 max_value = max(max_value, nums[2 * i + 1])
14 return max_valueℹ
Complexity note: The time complexity is O(n) because we only traverse the array once to fill it, and the space complexity is O(n) due to the storage of the nums array.
- 1The generated array follows a specific pattern based on the index, allowing for efficient calculation.
- 2Understanding the recursive nature of the array generation helps in optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.