DevPath

← All problems

Last Stone Weight

Easy heap · simulation

Description

Repeatedly smash the two heaviest stones: equal stones both vanish, otherwise the difference remains. Return the final weight, or 0 if none remain.

Constraints

1 <= n <= 1000

Examples

Input: stones = [2,7,4,1,8,1]

Output: 1

Hints (1)
  • Always take the two largest; a max-heap makes that cheap.

Solutions

Sort and smash. (requires "sort") · Time O(n^2 log n) · Space O(1)

func lastStoneWeight(stones []int) int {
    a := append([]int{}, stones...)
    for len(a) > 1 {
        sort.Sort(sort.Reverse(sort.IntSlice(a)))
        x, y := a[0], a[1]
        a = a[2:]
        if x != y {
            a = append(a, x-y)
        }
    }
    if len(a) == 0 {
        return 0
    }
    return a[0]
}

Create a free account to submit solutions, track progress and save problems.

Create account