Get Maximum in Generated Array — LeetCode 1646 Python Solution

EasyArraySimulation
Problem
#1646
Reading time
2 min

The 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​​​.

Example

Input
n = 7
Output
3
Explanation
According to the given rules:

Python solution

Python
class Solution:
    def getMaximumGenerated(self, n: int) -> int:
        if n < 2:
            return n
        nums = [0] * (n + 1)
        nums[1] = 1
        for i in range(2, n + 1):
            nums[i] = nums[i >> 1] if i % 2 == 0 else nums[i >> 1] + nums[(i >> 1) + 1]
        return max(nums)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1646. Get Maximum in Generated Array?
LeetCode 1646. Get Maximum in Generated Array is rated Easy on LeetCode.
What topics does LeetCode 1646. Get Maximum in Generated Array cover?
LeetCode 1646. Get Maximum in Generated Array is tagged Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview