ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • PROGRAMMERES Level 1 탐욕법(Greedy) 체육복 JAVA
    PROGRAMMERS/탐욕법(Greedy) 2022. 7. 21. 17:46
    import java.util.*;
    
    class Solution {
        public static int solution(int n, int[] lost, int[] reserve) {
            int count=0;
            // 최댓값을 구하는 것이기 때문에 정렬시켜서 앞에서부터 앞번호부터 진행해야한다
            // 예를들어 lost{4,2} reserve{3,5} 일 경우 정렬을 안시켜주면 4와 3이 짝이되어 2는 
            // 체육복을 못빌리지만 정렬을 시켜서 lost{2,4} reserve{3,5} 가 되면 2와 4 둘다 가능
            Arrays.sort(lost);
            Arrays.sort(reserve);
            
            for(int i=0; i<lost.length; i++){
                for(int j=0; j<reserve.length; j++){
                    if(lost[i]==reserve[j]) {
                        // i와 j를 따른 수로 초기화시켜줘야 중복이 안됨
                    	lost[i] = -100;
                     	reserve[j] = -200;
                    	count += 1;
                    	break;
                    }
                    	
                }
            }        
    
            for(int i=0; i<lost.length; i++){
                for(int j=0; j<reserve.length; j++){
                    if(Math.abs(lost[i]-reserve[j])==1) {
                        count += 1;
                        reserve[j]=-1;
                        break;                    
                    }
                }
            }
    
            int answer = n-lost.length + count;
            return answer;
            
            
        }
    }

    댓글

Designed by Tistory.