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
i
such that 2 <= i <= n
:
i
is even, nums[i] = nums[i / 2]
i
is odd, nums[i] = nums[i / 2] + nums[i / 2 + 1]
Return the maximum integer in the array nums
.
n
is 0?
nums[0]
is the only element in the array.n
?
n
is in the range [0, 100].n
is relatively small (up to 100), an O(n) solution is acceptable.To solve the problem, follow these steps:
nums
of size n + 1
and initialize the first two elements nums[0]
and nums[1]
as given.n
, and populate elements of nums
based on whether the current index i
is even or odd.def getMaximumGenerated(n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
nums = [0] * (n + 1)
nums[0], nums[1] = 0, 1
max_val = 1
for i in range(2, n + 1):
if i % 2 == 0:
nums[i] = nums[i // 2]
else:
nums[i] = nums[i // 2] + nums[(i // 2) + 1]
max_val = max(max_val, nums[i])
return max_val
n
times, and each iteration takes O(1) time, so the total complexity for this part is O(n).Hence, the overall time complexity is O(n), and the space complexity is O(n) due to the array nums
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?