[LeetCode] 2779. Maximum Beauty of an Array After Applying Operation (Python)

2024. 12. 11. 14:51·알고리즘/LeetCode

 

난이도: Medium

문제 설명


You are given a 0-indexed array nums and a non-negative integer k.

In one operation, you can do the following:

  • Choose an index i that hasn't been chosen before from the range [0, nums.length - 1].
  • Replace nums[i] with any integer from the range [nums[i] - k, nums[i] + k].

The beauty of the array is the length of the longest subsequence consisting of equal elements.

Return the maximum possible beauty of the array nums after applying the operation any number of times.

Note that you can apply the operation to each index only once.

A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.

 

문제 예제


Example 1:

Input: nums = [4,6,1,2], k = 2
Output: 3
Explanation: In this example, we apply the following operations:
- Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2].
- Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4].
After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3).
It can be proven that 3 is the maximum possible length we can achieve.

Example 2:

Input: nums = [1,1,1,1], k = 10
Output: 4
Explanation: In this example we dont have to apply any operations.
The beauty of the array nums is 4 (whole array).

 

제한사항


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

 

✏️Solution(솔루션)


class Solution:
    def maximumBeauty(self, nums: List[int], k: int) -> int:
        range_list = []
        n = len(nums)

        for num in nums:
            range_list.append((max(0, num-k), num+k))
        
        range_list.sort(key=lambda x:(x[0],x[1]))

        answer = 0

        for i in range(n):
            left, right = i, n - 1 
            while left <= right:
                mid = (left + right) // 2
                if range_list[mid][0] <= range_list[i][1]:
                    left = mid + 1
                else:
                    right = mid - 1

            answer = max(answer, right - i + 1)
        
        return answer

 

문제를 읽다 보니까 다음과 같이 최대한 많이 겹치는 수를 구하면 될 것 같았다.

 

문제 예제에서는 4로 했을 때 3개로 최대가 된다 했는데, 2나 3으로 해도 3개로 최대가 된다.

 

따라서, 각 nums의 요소마다 [num-k, num+k]의 범위를 저장하고, 정렬 시켜주었다.

 

그리고, 이진탐색을 통해 겹치지 않는 구간의 index를 찾았고, 그 index 기반으로 겹치는 수를 구했다.

 

이제 이것이 최대가 되는 값을 찾아 return 하였고, 정답을 맞출 수 있었다.

 

문제를 풀고 나니 시간과 메모리 둘다 효율성이 굉장히 낮게 나왔다.

 

다른 사람들의 풀이를 보니 굳이 이진 탐색을 사용할 필요가 없는 문제인 것 같았다...

 


2779. Maximum Beauty of an Array After Applying Operation

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 2593. Find Score of an Array After Marking All Elements (Python)  (0) 2024.12.13
[LeetCode] 2558. Take Gifts From the Richest Pile (Python)  (0) 2024.12.12
[LeetCode] 2981. Find Longest Special Substring That Occurs Thrice I (Python)  (0) 2024.12.10
[LeetCode] 3152. Special Array II (Python)  (2) 2024.12.09
[LeetCode] 2054. Two Best Non-Overlapping Events (Python)  (0) 2024.12.09
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 2593. Find Score of an Array After Marking All Elements (Python)
  • [LeetCode] 2558. Take Gifts From the Richest Pile (Python)
  • [LeetCode] 2981. Find Longest Special Substring That Occurs Thrice I (Python)
  • [LeetCode] 3152. Special Array II (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    알고리즘
    백트래킹
    우선순위큐
    도커
    이진탐색
    leetcode
    Apache Spark
    분산
    docker
    오블완
    티스토리챌린지
    문자열
    String
    리트코드
    파이썬
    그래프
    dfs
    프로그래머스
    쿠버네티스
    BFS
    programmers
    아파치 스파크
    heapq
    Python
    Kubernetes
    DP
    코딩테스트
    아파치 하둡
    분산처리
    누적합
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2779. Maximum Beauty of an Array After Applying Operation (Python)
상단으로

티스토리툴바