< All posts

2779. Maximum Beauty of an Array After Applying Operation

๋ฌธ์ œ ์„ค๋ช…

์ด ๋ฌธ์ œ๋Š” ๋‹ค์Œ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ–ˆ์„ ๋•Œ, ๊ฐ€์žฅ ํฐ beauty๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋•Œ, beauty๋Š” ๋™์ผํ•œ ์ˆซ์ž๊ฐ€ ์—ฌ๋Ÿฌ๋ฒˆ ๋‚˜์˜ค๋Š” subsequence์ด๋‹ค.

์—ฐ์‚ฐ:

  • nums์˜ ๋‘ ์ˆซ์ž๋ฅผ ์„ ํƒํ•œ๋‹ค. (nums[i], nums[j])
  • ์ˆซ์ž๋ฅผ [nums[i]-k, nums[i]+k] ์‚ฌ์ด์˜ ๊ฐ’์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

2779

ํ’€์ด ๋ฐ ํ•ด์„ค

1์ฐจ ํ’€์ด

a1

ํ…Œ์ผ€๋Š” ๋‹ค ํ†ต๊ณผํ–ˆ์œผ๋‚˜, 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)

Complexity Analysis

tc

์‹œ๊ฐ„ ๋ณต์žก๋„

  • O(n) : nums์˜ ๊ธธ์ด๋งŒํผ for loop์„ ๋Œ์•„์•ผ ํ•˜๋ฏ€๋กœ O(n)์ด๋‹ค.

๊ณต๊ฐ„ ๋ณต์žก๋„

  • O(n) : counts ๋ฐฐ์—ด์„ nums์˜ ์ตœ๋Œ€๊ฐ’ + k + 2๋งŒํผ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ O(n)์ด๋‹ค.

Constraint Analysis

Constraints:
1 <= nums.length <= 10^5
0 <= nums[i], k <= 10^5

References

ยฉ 2025 HyunJoon Sung. All Rights Reserved.

GitHub