[LeetCode] 3020. Find the Maximum Number of Elements in Subset

2026. 6. 28. 01:00·Algorithm/Review
728x90

https://leetcode.com/problems/find-the-maximum-number-of-elements-in-subset/description/?envType=daily-question&envId=2026-06-27

 

Find the Maximum Number of Elements in Subset - LeetCode

Can you solve this real interview question? Find the Maximum Number of Elements in Subset - You are given an array of positive integers nums. You need to select a subset of nums which satisfies the following condition: * You can place the selected elements

leetcode.com

 

문제 정의

1. nums라는 양의 정수 배열이 주어진다.

2. 이때 부분집합을 골라서 배열했을때 팰린드롬 모양(대칭)이 되어야 한다.

3. x, x^2, x^4 *** x^4, x^2, x 이런식으로 나와야 한다.

 

 

문제 접근

결국 양쪽 대칭이 되어야 하기 때문에 map을 사용해서 nums 라는 배열중 원소의 개수를 하나씩 다 세줘야 한다. 그 이유는 제일 높은 대칭 탑을 이루기 위해서는 각 원소가 2개 이상씩 있어야 하며 마지막 가장 높은 원소는 1개 이상이 있어야 한다.

 

map을 사용해서 개수를 세준 후 map을 순환하여 하나를 잡고 어디까지 올라갈 수 있는지 확인하며 최대 개수를 업데이트 해주었다.

 

작성 코드(C++)

class Solution {
public:
    int maximumLength(vector<int>& nums) {
        map<int, int> m;

        for(auto &iter : nums) m[iter]++;

        int result = 1;

        for(auto &iter : m) {
            long long val = iter.first;
            int count = iter.second;
            if(val == 1) continue;
            int len = 0;

            while(m.count(val) && m[val] >= 2) {
                len += 2;
                if(val > 1e9) {
                    val = -1;
                    break;
                }
                val = val * val;
            }

            len += (m.count(val)? 1 : -1);
            result = max(result, len);
        }

        if(m.count(1)) {
            int res = m[1];
            result = max(result, res % 2 == 1? res: res-1);
        }

        return result;
    }
};

 

 

작성코드(Java)

class Solution {
    public int maximumLength(int[] nums) {
        Map<Long, Integer> m = new HashMap<>();
        int result = 1;

        for(int a : nums) {
            m.put((long)a, m.getOrDefault((long)a, 0) + 1);
        }

        for(long key : m.keySet()) {
            long val = key;
            if(val == 1) continue;
            int count = m.get(key);
            int len = 0;

            while(m.containsKey(val) && m.get(val) >= 2) {
                len += 2;
                if(val >= Long.MAX_VALUE) {
                    val = -1;
                    break;
                }
                val = val * val;
            }

            result = Math.max(result, m.containsKey(val)? len+1 : len-1);
        }

        if(m.containsKey(1L)) {
            result = Math.max(result, m.get(1L) % 2 == 1? m.get(1L) : m.get(1L)-1);
        }

        return result;
    }
}

 

 

회고록(막힌 부분)

처음에 키포인트 대칭이기 때문에 2개 이상인것은 잘 잡아냈지만 해당 부분에서 따로 map을 2개 이상인 요소만 따로 리스트에 저장하여 어떻게 풀려고 했다 하지만 해당 부분에서 최대 길이를 구하기 위해 여러 요소들이 존재했기에 구현을 못했다.

728x90
저작자표시 (새창열림)

'Algorithm > Review' 카테고리의 다른 글

[LeetCode] 410. Split Array Largest Sum  (0) 2026.06.19
[백준] 2306번 유전자 (C++)  (0) 2026.03.19
[백준] 1315번 RPG (C++)  (0) 2026.03.15
'Algorithm/Review' 카테고리의 다른 글
  • [LeetCode] 410. Split Array Largest Sum
  • [백준] 2306번 유전자 (C++)
  • [백준] 1315번 RPG (C++)
쿨쿨.
쿨쿨.
  • 쿨쿨.
    All of the life
    쿨쿨.
  • 전체
    오늘
    어제
    • 분류 전체보기 (278)
      • Programming (47)
        • C, C++ (18)
        • Python (6)
        • Java (1)
        • HTML,CSS,JS (3)
        • SQL(DB) (13)
        • SpringBoot (3)
        • Android (2)
        • CI,CD (1)
      • Algorithm (173)
        • Review (4)
      • Security (14)
        • WebHacking (3)
        • Websecurity (11)
      • OS (19)
        • Linux (12)
        • Mac os (2)
      • 머신러닝 (1)
      • CS(Computer Science) (12)
        • 컴퓨터 네트워크 (3)
        • 컴퓨터 구조 (1)
        • 인공지능 (8)
      • Docker (1)
      • Dev Book Review (3)
        • Clean Code (1)
        • Effective Java (0)
        • Real MySQL (2)
      • SWM (1)
      • Review (5)
      • AWS (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Leviathan
    그래프 이론
    깊이우선탐색
    c언어
    구현
    다익스트라
    백준
    이분탐색
    DP
    그리디
    시뮬레이션
    코딩
    비트마스킹
    우선순위큐
    wargame
    linux
    정렬
    에라토스테네스의 체
    다이나믹 프로그래밍
    백트래킹
    WebSecurity
    Bandit
    브루트포스
    DFS
    재귀
    투포인터
    우선순위 큐
    누적합
    트리
    BFS
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.6
쿨쿨.
[LeetCode] 3020. Find the Maximum Number of Elements in Subset
상단으로

티스토리툴바