C++ Algorithm & Study/C++ & Algorithm Strategies

[Porgrammers] 최솟값 만들기

GameChoi 2022. 12. 16. 12:54

https://school.programmers.co.kr/learn/courses/30/lessons/12941

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

0. Headers

 - sort 사용하기 위한 algorithm

#include<vector>
#include <algorithm>
using namespace std;

 

1. 알고리즘

 - 각 배열의 곱(곱한 값은 다시X)이 최소가 되어야 한다면 A의 배열을 최소, B의 배열을 최대의 배열로 만들면 됨

 - std::sort를 사용 및 람다식을 사용하여 최소, 최대 배열을 구함

int solution(vector<int> A, vector<int> B)
{
    int answer = 0;
    sort(A.begin(), A.end(), [](int a, int b){return a> b;}); // 최소 배열
    sort(B.begin(), B.end(), [](int a, int b){return a< b;}); // 최대 배열
}

 - 각 배열을 곱함

int solution(vector<int> A, vector<int> B)
{
    int answer = 0;
    sort(A.begin(), A.end(), [](int a, int b){return a> b;});
    sort(B.begin(), B.end(), [](int a, int b){return a< b;});
    
    for (int i = 0; i < A.size(); i++) answer += A[i] * B[i]; // 곱
    
    return answer;
}

 

2. 완성 코드

#include<vector>
#include <algorithm>
using namespace std;

int solution(vector<int> A, vector<int> B)
{
    int answer = 0;
    sort(A.begin(), A.end(), [](int a, int b){return a> b;});
    sort(B.begin(), B.end(), [](int a, int b){return a< b;});
    
    for (int i = 0; i < A.size(); i++) answer += A[i] * B[i];
    
    return answer;
}

 

Test Code