[front end algorithm] 1046. The weight of the last stone, violent solution

Time:2021-6-14

There is a pile of stones, and the weight of each stone is a positive integer.

Each round, choose two of the heaviest stones, and then smash them together. Suppose the weight of the stone is x and Y respectively, and x < = y. The possible results of comminution are as follows:

  • If x = = y, both stones will be completely crushed;
  • If x= y. Then the stone with weight x will be completely crushed, and the new weight of the stone with weight y is y-x.
  • In the end, there’s only one stone left. Return the weight of this stone. If there is no stone left, return 0.
Example:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
First select 7 and 8 to get 1, so the array is converted to [2,4,1,1,1],
Then select 2 and 4 to get 2, so the array is converted to [2,1,1,1],
Then 2 and 1, get 1, so the array is converted to [1,1,1],
Finally, select 1 and 1, get 0, and finally convert the array to [1], which is the weight of the last remaining stone.

Tips:

  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 1000

How to solve the problem:

  • 1. Sort
  • 2. The largest minus the weight of the second largest stone
  • 3. Delete the second item and change the subtraction value of the first item;
  • 4. Reorder until the array length is less than 1

Problem solving code

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

results of enforcement

[front end algorithm] 1046. The weight of the last stone, violent solution