Skip to content

1646. Get Maximum in Generated Array 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int getMaximumGenerated(int n) {
    if (n == 0)
      return 0;
    if (n == 1)
      return 1;

    vector<int> nums(n + 1);
    nums[1] = 1;

    for (int i = 1; (2 * i + 1) <= n; ++i) {
      nums[2 * i] = nums[i];
      nums[2 * i + 1] = nums[i] + nums[i + 1];
    }

    return ranges::max(nums);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int getMaximumGenerated(int n) {
    if (n == 0)
      return 0;
    if (n == 1)
      return 1;

    int[] nums = new int[n + 1];
    nums[1] = 1;

    for (int i = 1; (2 * i + 1) <= n; ++i) {
      nums[2 * i] = nums[i];
      nums[2 * i + 1] = nums[i] + nums[i + 1];
    }

    return Arrays.stream(nums).max().getAsInt();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def getMaximumGenerated(self, n: int) -> int:
    if n == 0:
      return 0
    if n == 1:
      return 1

    nums = [0] * (n + 1)
    nums[1] = 1

    i = 1
    while 2 * i + 1 <= n:
      nums[2 * i] = nums[i]
      nums[2 * i + 1] = nums[i] + nums[i + 1]
      i += 1

    return max(nums)