Last Stone Weight
Easy heap · simulation
Description
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]
}
Sort and smash. · Time O(n^2 log n) · Space O(1)
function lastStoneWeight(stones) {
const a = [...stones];
while (a.length > 1) {
a.sort((x, y) => y - x);
const x = a.shift(), y = a.shift();
if (x !== y) a.push(x - y);
}
return a[0] ?? 0;
}
Sort and smash. · Time O(n^2 log n) · Space O(1)
function lastStoneWeight($stones) {
while (count($stones) > 1) {
rsort($stones);
$a = array_shift($stones);
$b = array_shift($stones);
if ($a !== $b) { $stones[] = $a - $b; }
}
return $stones[0] ?? 0;
}
Sort and smash. · Time O(n^2 log n) · Space O(1)
def lastStoneWeight(stones):
a = sorted(stones)
while len(a) > 1:
x = a.pop()
y = a.pop()
if x != y:
a.append(x - y)
a.sort()
return a[0] if a else 0
Sort and smash. · Time O(n^2 log n) · Space O(1)
function lastStoneWeight(stones: number[]): number {
const a = [...stones];
while (a.length > 1) {
a.sort((x, y) => y - x);
const x = a.shift()!, y = a.shift()!;
if (x !== y) a.push(x - y);
}
return a[0] ?? 0;
}
Create a free account to submit solutions, track progress and save problems.
Create account