안녕 세상아,

[프로그래머스/c++] Lv2. 과일 장수 본문

프로그래머스

[프로그래머스/c++] Lv2. 과일 장수

돈 많은 백수가 되고싶다 2024. 10. 22. 18:50

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

 

프로그래머스

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

programmers.co.kr

점수를 내림차순으로 정렬하여 높은 점수부터 상자를 채우는 방식이다. 

i + m - 1이 score.size()보다 작을 때만 계산한다. 인덱스가 넘지 않기 위해!

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

using namespace std;

int solution(int k, int m, vector<int> score) {
    int answer = 0;

    sort(score.begin(), score.end(), greater<>());
    for (int i = 0; i + m - 1 < score.size(); i += m) {
        answer += score[i + m - 1] * m;
    }

    return answer;
}