LeetCode - Problems - Algorithms - 1646. Get Maximum in Generated Array
Problem Description
You are given an integer n. An 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 1:
- Input: n = 7
- Output: 3
- Explanation: According to the given rules:
- nums[0] = 0
- nums[1] = 1
- nums[(1 * 2) = 2] = nums[1] = 1
- nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
- nums[(2 * 2) = 4] = nums[2] = 1
- nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
- nums[(3 * 2) = 6] = nums[3] = 2
- nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
- Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3.
Example 2:
- Input: n = 2
- Output: 1
- Explanation: According to the given rules, the maximum between nums[0], nums[1], and nums[2] is 1.
Example 3:
- Input: n = 3
- Output: 2
- Explanation: According to the given rules, the maximum between nums[0], nums[1], nums[2], and nums[3] is 2.
Constraints:
- 0 <= n <= 100
My Solution (Python)
class Solution(object):
def getMaximumGenerated(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return 1
nums = [] # empty array nums
nums.append(0) # nums[0]
nums.append(1) # nums[1]
index = 2 # index for nums
while index <= n:
quotient = int(index / 2)
remainder = index % 2
if remainder == 0: # index is even number
nums.append(nums[quotient])
else: # index is odd number
nums.append(nums[quotient] + nums[quotient + 1])
index += 1
return max(nums)
์ค๋ช ์ด ์กฐ๊ธ ๋ณต์กํด๋ณด์ด์ง๋ง ๋ถ์ํ๊ณ ๋ณด๋ฉด ์ฝ๋ค.
ํผ๋ณด๋์น์ ๋น์ทํ๊ฒ ๋ฐฐ์ด์ ๋ค์ด์๋ ์๋ฅผ ์ด์ฉํด ๋ค์ ์ฌ ์ซ์๋ฅผ ๊ณ์ฐํ๋ฉด ๋๋ค.
๋ฐฐ์ด์ ๊ท์น์ ํฌ๊ฒ ๋๊ฐ์ง:
- index number๊ฐ ํ์์ผ ๊ฒฝ์ฐ, index number๊ฐ ๊ทธ ์๋ฅผ ๋๋ ๋ชซ์ธ nums array์ ์์์, ๊ทธ ๋ค์ ์์๋ฅผ ๋ํ ๊ฐ
- index number๊ฐ ์ง์์ผ ๊ฒฝ์ฐ, index number๊ฐ ๊ทธ ์๋ฅผ ๋๋ ๋ชซ์ธ nums array์ ์์์ ๊ฐ
ํ์ด๊ณผ์ :
- nums[0]๊ณผ nums[1]์ ๊ฐ์ ์ด๋ฏธ ์ ํด์ ธ์์ผ๋ n์ด 0 ํน์ 1์ธ์ง ํ์ธํ ํ ์ ํด์ง ๊ฐ์ ๋ฐํํ๋ค.
- 0์ด๋ 1์ด ์๋ ๊ฒฝ์ฐ nums array๋ฅผ ์ํ ๋น ๋ฐฐ์ด์ ์์ฑํ๋ค. ์ ํด์ง nums[0]๊ณผ nums[1]์ ๊ฐ์ ์ถ๊ฐํ๋ค.
- index๋ ํ์ฌ ๋ฐฐ์ด์ ์ง์ ๋ ๋ง์ง๋ง ๊ฐ์ ๋ค์ ์์๋ฅผ ์ํ ์ธ๋ฑ์ค ๋๋ฒ. 0๊ณผ 1์ ์ด๋ฏธ ์ฑ์ ์ผ๋ 2๋ก ์ด๊ธฐํํ๋ค.
- ๋ฐ๋ณต๋ฌธ: index๊ฐ n๋ณด๋ค ๊ฐ๊ฑฐ๋ ์์๋๊น์ง
- index๋ฅผ 2๋ก ๋๋ ๋ชซ๊ณผ ๋๋จธ์ง๋ฅผ ๊ณ์ฐํ๋ค.
- index๊ฐ ์ง์์ผ๊ฒฝ์ฐ nums[๋ชซ]์ ๋ฐฐ์ด์ ์ถ๊ฐํ๋ค.
- index๊ฐ ํ์์ผ๊ฒฝ์ฐ nums[๋ชซ]๊ณผ nums[๋ชซ+1] ๊ฐ์ ๋ฐฐ์ด์ ์ถ๊ฐํ๋ค.
- ๋ฐ๋ณต์ ๋๋ง์น๊ธฐ ์ ์ index ๋๋ฒ๋ฅผ 1 ์ฆ๊ฐ์ํจ๋ค.
- nums array์ ์ต๋๊ฐ์ ๋ฐํํ๋ค.
'Problem solving > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 7. Reverse Integer (C#) (0) | 2021.01.23 |
---|---|
[LeetCode] 1. Two Sum (C#) (0) | 2021.01.21 |
[LeetCode]Daily Challenge: Boats to Save People (Python) (0) | 2021.01.13 |
[LeetCode] Daily Challenge: Add Two Numbers (Python) (0) | 2021.01.13 |
[LeetCode] Daily Challenge Merge Sorted Array (Python) (0) | 2021.01.12 |