🍞 Problem Solving/Programmers

[프로그래머스][Level1] 최소 직사각형 c++

박빵이 2022. 9. 2. 01:43

가로와 세로의 길이 중에 통틀어서 가장 긴 길이를 찾는다.  
그 길이의 명함 번호 인덱스 값과 가로세로 인덱스 값을 저장한다.

만약 가로의 길이가 가장 긴 길이라면, 세로의 길이들을 비교해서  
가로의 길이보다 세로의 길이가 길다면 값을 서로 바꿔줬다.

만약 세로의 길이가 가장 긴 길이라면, 가로의 길이들을 비교해서  
세로의 길이보다 가로의 길이가 길다면 값을 서로 바꿔줬다.

 

풀이

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<vector<int>> sizes) {
    int answer = 0;
    
    // 가장 길이가 긴 곳 찾기 (가로인지 세로인지)
    int maxLength = 0, row, col;
    for(int i = 0; i < sizes.size(); i++){
        for(int j = 0; j < sizes[i].size(); j++){
            if (maxLength < sizes[i][j]) {
                maxLength = sizes[i][j];
                row = i; // 몇 번째인지
                col = j; // 가로인지 세로인지
            }
        }
    }
    
    int res = 0;
    // 가로가 가장 길다면
    if (col == 0) {
        for(int i = 0; i < sizes.size(); i++){
            if (sizes[i][0] < sizes[i][1]) {
                swap(sizes[i][0], sizes[i][1]);
            }
            res = max(res, sizes[i][1]);
        }
    }
    // 세로가 가장 길다면
    else {
        for(int i = 0; i < sizes.size(); i++){
            if (sizes[i][0] > sizes[i][1]) {
                swap(sizes[i][0], sizes[i][1]);
            }
            res = max(res, sizes[i][0]);
        }
    }
    answer = maxLength * res;
    
    return answer;
}