Facebook Pixel

1646. Get Maximum in Generated Array

EasyArraySimulation
Leetcode Link

Problem Description

You need to generate an array of integers following specific rules and find the maximum value in that array.

Given an integer n, you'll create an array nums with length n + 1 (indices from 0 to n) using these rules:

  1. Start with nums[0] = 0
  2. Set nums[1] = 1
  3. For even indices: When i is even and 2 ≤ i ≤ n, set nums[i] = nums[i/2]
  4. For odd indices: When i is odd and 2 ≤ i ≤ n, set nums[i] = nums[i/2] + nums[i/2 + 1]

The pattern creates a sequence where:

  • Even-indexed elements copy their value from the element at half their index
  • Odd-indexed elements sum the values from two consecutive elements starting at half their index (rounded down)

For example, if n = 7:

  • nums[0] = 0
  • nums[1] = 1
  • nums[2] = nums[1] = 1
  • nums[3] = nums[1] + nums[2] = 1 + 1 = 2
  • nums[4] = nums[2] = 1
  • nums[5] = nums[2] + nums[3] = 1 + 2 = 3
  • nums[6] = nums[3] = 2
  • nums[7] = nums[3] + nums[4] = 2 + 1 = 3

The resulting array would be [0, 1, 1, 2, 1, 3, 2, 3], and the maximum value is 3.

Your task is to generate this array according to the rules and return the maximum integer found in it.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The problem asks us to build an array following specific generation rules and find its maximum value. The key insight is that we need to construct the entire array first before finding the maximum, since the values depend on previously computed elements.

Looking at the generation rules, we notice that each element's value depends only on elements with smaller indices. This means we can build the array iteratively from left to right. For any index i:

  • If i is even, we simply copy the value from index i/2
  • If i is odd, we sum the values from indices i/2 and i/2 + 1 (using integer division)

The relationship can be rewritten using bit operations for efficiency. Since dividing by 2 is equivalent to right-shifting by 1 bit (i >> 1), we can express:

  • For even i: nums[i] = nums[i >> 1]
  • For odd i: nums[i] = nums[i >> 1] + nums[(i >> 1) + 1]

The base cases nums[0] = 0 and nums[1] = 1 are given directly. For n < 2, we can return n immediately since nums[0] = 0 when n = 0 and nums[1] = 1 when n = 1.

Once we've generated all values up to index n, we simply scan through the array to find the maximum value. The approach is straightforward: generate the sequence according to the rules, then return the largest element.

Solution Approach

The implementation follows a straightforward simulation approach to generate the array according to the given rules.

First, we handle the edge cases where n < 2. If n = 0, we return 0, and if n = 1, we return 1, since these are the maximum values in their respective arrays.

For n ≥ 2, we create an array nums of size n + 1 initialized with zeros. We then set the base values:

  • nums[0] = 0 (already set by initialization)
  • nums[1] = 1

Next, we iterate through indices from 2 to n (inclusive) and populate each element based on whether the index is even or odd:

for i in range(2, n + 1):
    if i % 2 == 0:  # even index
        nums[i] = nums[i >> 1]
    else:  # odd index
        nums[i] = nums[i >> 1] + nums[(i >> 1) + 1]

The bit shift operation i >> 1 is used to efficiently compute i // 2. This works because right-shifting a binary number by one position is equivalent to integer division by 2.

The conditional expression can be written more concisely using a ternary operator:

nums[i] = nums[i >> 1] if i % 2 == 0 else nums[i >> 1] + nums[(i >> 1) + 1]

After generating all elements up to index n, we use Python's built-in max() function to find and return the maximum value in the array.

The time complexity is O(n) since we iterate through each index once to generate the array and then scan it once more to find the maximum. The space complexity is also O(n) for storing the generated array.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with n = 5 to understand how the algorithm works step by step.

Step 1: Initialize

  • Create array nums of size 6 (indices 0 to 5)
  • Set nums[0] = 0 and nums[1] = 1
  • Current array: [0, 1, _, _, _, _]

Step 2: Generate index 2 (even)

  • Since 2 is even, apply rule: nums[2] = nums[2 >> 1] = nums[1] = 1
  • Current array: [0, 1, 1, _, _, _]

Step 3: Generate index 3 (odd)

  • Since 3 is odd, apply rule: nums[3] = nums[3 >> 1] + nums[(3 >> 1) + 1]
  • Calculate: nums[3] = nums[1] + nums[2] = 1 + 1 = 2
  • Current array: [0, 1, 1, 2, _, _]

Step 4: Generate index 4 (even)

  • Since 4 is even, apply rule: nums[4] = nums[4 >> 1] = nums[2] = 1
  • Current array: [0, 1, 1, 2, 1, _]

Step 5: Generate index 5 (odd)

  • Since 5 is odd, apply rule: nums[5] = nums[5 >> 1] + nums[(5 >> 1) + 1]
  • Calculate: nums[5] = nums[2] + nums[3] = 1 + 2 = 3
  • Final array: [0, 1, 1, 2, 1, 3]

Step 6: Find maximum

  • Scan through the array: max(0, 1, 1, 2, 1, 3) = 3
  • Return 3

The algorithm correctly generates the sequence by using previously computed values, where even indices copy from their half-index position, and odd indices sum two consecutive elements starting from their half-index position.

Solution Implementation

1class Solution:
2    def getMaximumGenerated(self, n: int) -> int:
3        # Handle base cases where n is 0 or 1
4        if n < 2:
5            return n
6      
7        # Initialize array to store generated sequence
8        nums = [0] * (n + 1)
9        nums[1] = 1
10      
11        # Generate the sequence according to the rules:
12        # - If index i is even: nums[i] = nums[i/2]
13        # - If index i is odd: nums[i] = nums[i/2] + nums[i/2 + 1]
14        for i in range(2, n + 1):
15            if i % 2 == 0:
16                # Even index: value equals the value at half the index
17                nums[i] = nums[i >> 1]
18            else:
19                # Odd index: value equals sum of values at floor(i/2) and floor(i/2) + 1
20                nums[i] = nums[i >> 1] + nums[(i >> 1) + 1]
21      
22        # Return the maximum value in the generated array
23        return max(nums)
24
1class Solution {
2    public int getMaximumGenerated(int n) {
3        // Base case: if n is 0 or 1, return n itself
4        if (n < 2) {
5            return n;
6        }
7      
8        // Initialize array to store generated numbers
9        int[] nums = new int[n + 1];
10      
11        // Set base values according to the problem rules
12        nums[0] = 0;  // nums[0] = 0 (implicit due to array initialization)
13        nums[1] = 1;  // nums[1] = 1
14      
15        // Generate remaining numbers based on the given rules
16        for (int i = 2; i <= n; i++) {
17            if (i % 2 == 0) {
18                // For even index: nums[i] = nums[i / 2]
19                nums[i] = nums[i / 2];
20            } else {
21                // For odd index: nums[i] = nums[i / 2] + nums[i / 2 + 1]
22                nums[i] = nums[i / 2] + nums[i / 2 + 1];
23            }
24        }
25      
26        // Find and return the maximum value in the generated array
27        int maxValue = 0;
28        for (int i = 0; i <= n; i++) {
29            maxValue = Math.max(maxValue, nums[i]);
30        }
31      
32        return maxValue;
33    }
34}
35
1class Solution {
2public:
3    int getMaximumGenerated(int n) {
4        // Handle base cases where n is 0 or 1
5        if (n < 2) {
6            return n;
7        }
8      
9        // Create array to store the generated sequence
10        int nums[n + 1];
11      
12        // Initialize base values according to the problem rules
13        nums[0] = 0;
14        nums[1] = 1;
15      
16        // Generate the sequence based on the given rules:
17        // - If index i is even: nums[i] = nums[i/2]
18        // - If index i is odd: nums[i] = nums[i/2] + nums[i/2 + 1]
19        for (int i = 2; i <= n; ++i) {
20            if (i % 2 == 0) {
21                // Even index: value equals the value at index i/2
22                nums[i] = nums[i >> 1];
23            } else {
24                // Odd index: value equals sum of values at index i/2 and i/2+1
25                nums[i] = nums[i >> 1] + nums[(i >> 1) + 1];
26            }
27        }
28      
29        // Find and return the maximum value in the generated array
30        return *max_element(nums, nums + n + 1);
31    }
32};
33
1/**
2 * Generates an array based on specific rules and returns the maximum value.
3 * Rules:
4 * - nums[0] = 0
5 * - nums[1] = 1
6 * - nums[2 * i] = nums[i] when 2 * i <= n
7 * - nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 * i + 1 <= n
8 * 
9 * @param n - The upper bound index for the generated array
10 * @returns The maximum value in the generated array
11 */
12function getMaximumGenerated(n: number): number {
13    // Handle edge case where n is 0
14    if (n === 0) {
15        return 0;
16    }
17  
18    // Initialize array with size n + 1, filled with zeros
19    const nums: number[] = new Array(n + 1).fill(0);
20  
21    // Set base case: nums[1] = 1
22    nums[1] = 1;
23  
24    // Generate array values according to the rules
25    for (let i = 2; i <= n; i++) {
26        if (i % 2 === 0) {
27            // Even index: nums[i] = nums[i / 2]
28            nums[i] = nums[i >> 1];
29        } else {
30            // Odd index: nums[i] = nums[i / 2] + nums[i / 2 + 1]
31            nums[i] = nums[i >> 1] + nums[(i >> 1) + 1];
32        }
33    }
34  
35    // Return the maximum value in the array
36    return Math.max(...nums);
37}
38

Time and Space Complexity

Time Complexity: O(n)

The algorithm iterates through a loop from index 2 to n (inclusive), performing constant-time operations for each iteration. The loop runs n - 1 times. After the loop, finding the maximum value in the array requires another O(n) operation using the max() function. Therefore, the overall time complexity is O(n) + O(n) = O(n).

Space Complexity: O(n)

The algorithm creates an array nums of size n + 1 to store the generated sequence. This requires O(n + 1) = O(n) extra space. No other significant auxiliary space is used besides a few variables for indexing and temporary storage, which take O(1) space. Therefore, the total space complexity is O(n).

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Off-by-One Error with Array Size

A frequent mistake is creating an array of size n instead of n + 1. The problem requires generating elements from index 0 to n (inclusive), which means we need n + 1 elements total.

Incorrect:

nums = [0] * n  # Wrong: creates array of size n

Correct:

nums = [0] * (n + 1)  # Correct: creates array of size n + 1

2. Incorrect Handling of Edge Cases

Failing to properly handle the cases where n = 0 or n = 1 can lead to index errors or incorrect results. When n = 0, the array should only contain [0], and when n = 1, it should contain [0, 1].

Incorrect:

def getMaximumGenerated(self, n: int) -> int:
    nums = [0] * (n + 1)
    nums[1] = 1  # IndexError when n = 0

Correct:

def getMaximumGenerated(self, n: int) -> int:
    if n < 2:
        return n
    nums = [0] * (n + 1)
    nums[1] = 1

3. Misunderstanding Integer Division for Odd Indices

For odd indices, the formula uses i/2 which in the context means integer division (floor division). Using regular division or misinterpreting the indices can lead to wrong calculations.

Incorrect:

# Using i/2 - 1 and i/2 instead of i/2 and i/2 + 1
nums[i] = nums[i // 2 - 1] + nums[i // 2]  # Wrong indices

Correct:

# For odd i: nums[i] = nums[i/2] + nums[i/2 + 1]
# Where i/2 means integer division
nums[i] = nums[i // 2] + nums[i // 2 + 1]

4. Finding Maximum Before Completing Array Generation

Attempting to track the maximum value during generation but forgetting to compare with all elements can miss the actual maximum.

Incorrect:

max_val = 1
for i in range(2, n + 1):
    # ... generate nums[i] ...
    max_val = max(max_val, nums[i])
return max_val  # Might miss nums[1] = 1 being the maximum for small n

Correct:

# Generate entire array first, then find maximum
for i in range(2, n + 1):
    # ... generate nums[i] ...
return max(nums)  # Considers all elements including nums[0] and nums[1]
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement recursion?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More