[LeetCode] 3684. Maximize Sum of At Most K Distinct Elements

Chobby·2026년 1월 21일

LeetCode

목록 보기
945/989

😎풀이

  1. nums 오름차 순 정렬
  2. 큰 수부터 차례대로 추출하여 k개의 고유한 요소 수집
  3. 수집된 요소 반환
function maxKDistinct(nums: number[], k: number): number[] {
    const sorted = nums.toSorted((a, b) => a - b)
    const seen = new Set()
    const distincts = []
    while(distincts.length < k && sorted.length) {
        const poped = sorted.pop()
        if(seen.has(poped)) continue
        seen.add(poped)
        distincts.push(poped)
    }
    return distincts
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글