본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1431. Kids With the Greatest Number of Candies

반응형

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

가진 사탕의 최댓값 maxRepresentCandyNum와 정답을 저장할 변수 canTakeMaxCandies를 선언해 적절히 초기화해 줍니다.

📔 풀이과정

candies에 대해 loop를 수행합니다.

1. 현재 사탕 개수에 extraCandies를 받았을 때 maxRepresentCandyNum이상이라면 true를, 아니라면 false를 canTakeMaxCandies에 push_back해줍니다.

📔 정답 출력 | 반환

canTakeMaxCandies를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
        int maxRepresentCandyNum = 0;
        vector <bool> canTakeMaxCandies;
        
        for(auto c : candies) {
            maxRepresentCandyNum = max(maxRepresentCandyNum, c);
        }
        
        for(auto c : candies) {
            if(c + extraCandies >= maxRepresentCandyNum) {
                canTakeMaxCandies.push_back(true);
            } else {
                canTakeMaxCandies.push_back(false);
            }
        }
        return canTakeMaxCandies;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.