๋ฌธ์ ๋งํฌ
Maximum Bags With Full Capacity of Rocks - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
๋์ ๋ด์ ์ ์๋ ์ฉ๋ : capacity
ํ์ฌ ๋ด๊ฒจ์๋ ๋ : rocks
์ถ๊ฐ๋ก ๋ด์ ์ ์๋ ๋์ ๊ฐ์ : additionalRocks
์์ ๊ฐ๋ค์ด ์ฃผ์ด์ก์๋ "ํ์ฌ ๋ด๊ฒจ์๋ ๋"์์ ๋์ ๋ ์ถ๊ฐํด์ "๋์ ๋ด์ ์ ์๋ ์ฉ๋"์ ์ต๋ํ ์ฑ์ฐ๊ณ , ์ด๋ ๋ชจ๋ ์ฑ์์ง capacity์ ๊ฐ์๋ฅผ return ํ์ฌ๋ผ.
[2,3,4,5]๋ผ๋ capacity๊ฐ ์ฃผ์ด์ง๊ณ , [1,2,4,5]๋ผ๋ ํ์ฌ ๋ด๊ธด ๋์ด ์ฃผ์ด์ก์๋
additionalRocks = 1 ์ด๋ผ๋ฉด [2,2,4,5] ๋๋ [1,3,4,5]๋ฅผ ๋ง๋ค ์ ์๊ณ , ๋ชจ๋ ๊ฐ๋์ฐฌ capacity๋ 3๊ฐ ์ด๋ฏ๋ก 3์ return ํ๋ค.
์ ๊ทผ ๋ฐฉ๋ฒ
1. ์ฃผ์ด์ง ๋ฐฐ์ด capacity์ rocks๋ฅผ ์๋ก ๋บ ๋ฐฐ์ด์ ์์ฑํ๋ค. (๋ชจ์๋ ๋์ ๊ฐ์๋ฅผ ์๋ฏธํ๋ ๋ฐฐ์ด)
let needRocks = capacity.map((rock, idx) => { return rock - rocks[idx]; });โ
2. needRocks๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ๊ณ , ์กฐ๊ธ ํ์ํ ๋๋ถํฐ ์ฑ์ฐ๋ ๋ฐฉํฅ์ผ๋ก ์งํํ๋ค.needRocks.sort((a, b) => a - b);
ํ์ํ ๋์ด 1๊ฐ ์ด์์ด๋ผ๋ฉด additionalRocks์ ํ์ํ ๋์ ๋บ๋ค.
3. ํ์ํ ๋์ด 0๊ฐ๋ฉด output++;
needRocks.forEach(rock => { if(rock === 0) output++; else{ additionalRocks -= rock; if(additionalRocks >= 0) output++; else return false; } })โ
ํ์ํ ๋์ด 1๊ฐ ์ด์์ด๋ผ์ additionalRocks์์ ํ์ํ ๋์ ๋บ์ ๋,
addtionalRocks๊ฐ 0๊ฐ ์ด์์ด์ฌ์ผ output++์ ํ๊ณ , ์๋๋ผ๋ฉด ๋ฐ๋ณต๋ฌธ์ ๋ฉ์ถ๋ค.
/**
* @param {number[]} capacity
* @param {number[]} rocks
* @param {number} additionalRocks
* @return {number}
*/
var maximumBags = function(capacity, rocks, additionalRocks) {
let output = 0;
let needRocks = capacity.map((rock, idx) => {
return rock - rocks[idx];
});
needRocks.sort((a, b) => a - b);
needRocks.forEach(rock => {
if(rock === 0) output++;
else{
additionalRocks -= rock;
if(additionalRocks >= 0) output++;
else return false;
}
})
return output;
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Candy (0) | 2022.07.04 |
---|---|
[LeetCode] Maximum Area Of A Piece Of Cake After Horizontal And Vertical Cuts (0) | 2022.07.02 |
[LeetCode] Maximum Units On A Truck (0) | 2022.07.01 |
[LeetCode] Minimum Deletions To Make Character Frequencies Unique (0) | 2022.06.28 |
[LeetCode]Maximum Points You Can Obtain From Cards (0) | 2022.06.26 |