혼자 놀기의 달인

JJW·2024년 12월 16일

코딩 테스트

목록 보기
23/23

문제



문제 풀이

using System;
using System.Collections.Generic;

public class Solution 
{
    public int solution(int[] cards) 
    {
        int n = cards.Length;
        bool[] visited = new bool[n];
        List<int> cycles = new List<int>();

        for(int i = 0; i < n; i++)
        {
            if(!visited[i])
            {
                int count = 0;
                int j = i;
                while(!visited[j])
                {
                    visited[j] = true;
                    j = cards[j] - 1; // 카드의 번호는 1부터 시작하므로 인덱스 보정을 합니다.
                    count++;
                }
                cycles.Add(count);
            }
        }

        // 사이클 크기를 내림차순으로 정렬합니다.
        cycles.Sort((a, b) => b.CompareTo(a));

        if(cycles.Count < 2)
            return 0;
        else
            return cycles[0] * cycles[1];
    }
}
profile
Unity 게임 개발자를 준비하는 취업준비생입니다..

0개의 댓글