PS/LeetCode

LeetCode / Heap / 1046번 / Last Stone Weight / JS

KimMinJun 2023. 4. 18. 01:37

< 문제 바로가기 >

 

Last Stone Weight - LeetCode

Can you solve this real interview question? Last Stone Weight - You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them

leetcode.com

 

< 문제 간단설명 >

돌의 무게들이 배열로 들어온다. 그 중에서 가장 큰 두개의 돌의 무게를 x와 y라고 한다. 이때 x는 y이하이다.

  • 만약 x와 y가 같다면 둘다 없앤다.
  • 만약 x와 y가 같지 않다면 x는 없애고 y는 y-x로 대체한다.
  • 마지막 하나가 남을 때 까지 반복하여 마지막으로 남은 돌의 무게를 반환한다. 만약 남지 않았다면 0을 반환한다.

 

/**
 * @param {number[]} stones
 * @return {number}
 */
var lastStoneWeight = function(stones) {
    let [first, second] = [0, 0];
    while(stones.length > 1) {
        stones.sort((a, b) => a - b);
        first = stones.pop();
        second = stones.pop();

        if(first === second) {
            continue;
        }
        stones.push(Math.abs(first - second));
    }

    return stones;
}