[LeetCode] Water Bottles

준규·2022년 12월 31일
0

1.문제


There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.


처음에 물이 가득 차 있는 병인 numbottles 가 있다. numExchange만큼의 병을 새로운 물 하나로 바꿀 수 있을 때 한번의 operation에 새 물병 하나를 마셔서 빈 물병으로 만든다고 한다.

numBottles, numExchange 가 주어질 때 마실 수 있는 물병의 수의 최댓값을 리턴하는 문제이다.


Example 1

Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.

Example 2

Input: numBottles = 15, numExchange = 4

Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle. 
Number of water bottles you can drink: 15 + 3 + 1 = 19.

Constraints:

  • 1 <= numBottles <= 100
  • 2 <= numExchange <= 100

2.풀이

/**
 * @param {number} numBottles
 * @param {number} numExchange
 * @return {number}
 */
const numWaterBottles = function(numBottles, numExchange) {
    let result = 0;
    let currentExchange = 0;
    while(numBottles > 0) {
        // 현재 마실 수 있는 음료 갯수를 더한다
        result += numBottles;
        // 현재 가지고 있는 빈병의 수 갱신
        currentExchange = currentExchange + numBottles;
        // 빈병을 새 음료수로 교환한다.
        numBottles = Math.floor(currentExchange / numExchange);
        // 현재 가지고 있는 빈병의 수를 다시 갱신해준다
        currentExchange -= numBottles * numExchange;
    }

    return result
};

3.결과

profile
안녕하세요 :)

0개의 댓글