December 11, 2024
์ด ๋ฌธ์ ๋ ๋ค์ ์ฐ์ฐ์ ์ํํ์ ๋, ๊ฐ์ฅ ํฐ beauty๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค. ์ด๋, beauty๋ ๋์ผํ ์ซ์๊ฐ ์ฌ๋ฌ๋ฒ ๋์ค๋ subsequence์ด๋ค.
์ฐ์ฐ:
ํ ์ผ๋ ๋ค ํต๊ณผํ์ผ๋, TLE๋ก ์คํจ. ์ด๋ป๊ฒ ๋ ๋นจ๋ฆฌ ํ ์ ์์๊น? ์๋ฌด๋๋ for loop ๋๊ฐ ๋๋ฆฌ๋ฉด์ ๋๋ ค์ง๋๊ฒ ๊ฐ๊ธด ํ๋ค.
์ด๋ฅผ ์ด๋ป๊ฒ ๋ ๋น ๋ฅด๊ฒ ์ธ ์ ์์์ง ๊ณ ๋ฏผํ๋ค๊ฐ, difference array๋ฅผ ์ ํํ๊ฒ ๋์๋ค. ์ด๋ ์ ์ผ ๋จผ์ ์์ ๋์จ ์๋ฅผ ๋ํ๊ณ , ๋ง์ง๋ง ๋์จ ์๋ฅผ ๋นผ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ ์ ์๋ค.
๊ทธ๋ ๊ฒ ํ๋ค๋ฉด O(n)์ผ๋ก ๊ตฌํ์ด ๊ฐ๋ฅํ๋ค.
class Solution:
def maximumBeauty(self, nums: List[int], k: int) -> int:
# Handle edge case where nums is empty
if not nums:
return 0
max_num = max(nums)
# Initialize counts and a difference array
counts = [0] * (max_num + k + 2) # One extra for boundary handling
n = len(nums)
# Update the difference array based on each number in nums
for i in range(n):
start = max(0, nums[i] - k)
end = min(max_num + k, nums[i] + k)
counts[start] += 1 # Increment at start index
counts[end + 1] -= 1 # Decrement just past end index
# Apply the difference array to get the actual counts
for i in range(1, len(counts)):
counts[i] += counts[i - 1]
# The maximum value in counts is the answer
return max(counts)
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i], k <= 10^5