Skip to content

Commit 9ee8d89

Browse files
committed
Solution to 1046
1 parent b60c754 commit 9ee8d89

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

src/unresolved/1046.last-stone-weight.jl renamed to src/problems/1046.last-stone-weight.jl

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# ---
22
# title: 1046. Last Stone Weight
33
# id: problem1046
4-
# author: Tian Jun
5-
# date: 2020-10-31
4+
# author: Queensley E
5+
# date: 2024-12-11
66
# difficulty: Easy
77
# categories: Heap, Greedy
88
# link: <https://leetcode.com/problems/last-stone-weight/description/>
@@ -44,7 +44,33 @@
4444
#
4545
#
4646
## @lc code=start
47-
using LeetCode
47+
# using LeetCode
48+
49+
using DataStructures
50+
51+
function last_stone_weight(stones::Vector{Int64})
52+
# Create a PriorityQueue with unique identifiers for each stone
53+
heap = PriorityQueue{Tuple{Int64, Int64}, Int64}()
54+
for (i, stone) in enumerate(stones)
55+
enqueue!(heap, (stone, i), -stone) # Use negative stone value for max-heap
56+
end
57+
58+
while length(heap) > 1
59+
# Extract the two largest stones
60+
largest, _ = dequeue!(heap)
61+
second_largest, _ = dequeue!(heap)
62+
63+
# If they are not the same, calculate the difference and enqueue it
64+
if largest != second_largest
65+
enqueue!(heap, (largest - second_largest, length(heap) + 1), -(largest - second_largest))
66+
end
67+
end
68+
69+
# Return the last stone or 0 if the heap is empty
70+
return isempty(heap) ? 0 : first(first(collect(keys(heap))))
71+
end
72+
73+
last_stone_weight([2, 7, 4, 1, 8, 2])
4874

4975
## add your code here:
5076
## @lc code=end
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using Test
2+
3+
@testset "1046.last-stone-weight.jl" begin
4+
5+
@test last_stone_weight([2, 7, 4, 1, 8, 1]) == 1 # Problem example
6+
@test last_stone_weight([1, 1]) == 0 # All stones cancel out
7+
@test last_stone_weight([5]) == 5 # Single stone
8+
@test last_stone_weight([10, 4, 3]) == 3 # Large differences
9+
@test last_stone_weight([8, 8, 2, 2, 3]) == 1 # Mixed case
10+
@test last_stone_weight([7, 6, 7, 6]) == 0 # Multiple canceling pairs
11+
12+
end

0 commit comments

Comments
 (0)