반응형
https://leetcode.com/problems/distribute-candies-to-people/description/
Distribute Candies to People - LeetCode
Can you solve this real interview question? Distribute Candies to People - We distribute some number of candies, to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
num_people만큼의 크기를 가진 vector ans를 선언 후 0으로 모두 초기화해줍니다.
📔 풀이과정
사탕이 동날 때까지 사탕을 배분해주면 됩니다.
즉, 동날 때까지 while loop를 수행하며 나눠줄 사탕 개수 cnt만큼의 사탕을 나눠주되, 남은 사탕의 개수가 cnt이상인 경우에만 수행하고 아닌 경우에는 남은 사탕을 준 후 loop를 탈출해줍니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
vector<int> distributeCandies(int candies, int num_people) {
vector <int> ans(num_people, 0);
int cnt = 1;
while(candies>=0) {
for(int i = 0; i < num_people; i++) {
if(candies < cnt) {
ans[i] += candies;
candies -= cnt;
break;
}
ans[i] += cnt;
candies -= cnt;
cnt++;
}
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1175. Prime Arrangements (2) | 2023.11.20 |
---|---|
(C++) - LeetCode (easy) 1154. Day of the Year (0) | 2023.11.14 |
(C++) - LeetCode (easy) 1089. Duplicate Zeros (0) | 2023.10.27 |
(SQL) - LeetCode (easy) 1068. Product Sales Analysis I (0) | 2023.10.20 |
(C++) - LeetCode (easy) 1046. Last Stone Weight (0) | 2023.10.16 |