Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution to 1046 #176

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ---
# title: 1046. Last Stone Weight
# id: problem1046
# author: Tian Jun
# date: 2020-10-31
# author: Queensley E
# date: 2024-12-11
# difficulty: Easy
# categories: Heap, Greedy
# link: <https://leetcode.com/problems/last-stone-weight/description/>
Expand Down Expand Up @@ -46,5 +46,31 @@
## @lc code=start
using LeetCode

using DataStructures

function last_stone_weight(stones::Vector{Int64})
# Create a PriorityQueue with unique identifiers for each stone
heap = PriorityQueue{Tuple{Int64, Int64}, Int64}()
for (i, stone) in enumerate(stones)
enqueue!(heap, (stone, i), -stone) # Use negative stone value for max-heap
end

while length(heap) > 1
# Extract the two largest stones
largest, _ = dequeue!(heap)
second_largest, _ = dequeue!(heap)

# If they are not the same, calculate the difference and enqueue it
if largest != second_largest
enqueue!(heap, (largest - second_largest, length(heap) + 1), -(largest - second_largest))
end
end

# Return the last stone or 0 if the heap is empty
return isempty(heap) ? 0 : first(first(collect(keys(heap))))
end

last_stone_weight([2, 7, 4, 1, 8, 2])

## add your code here:
## @lc code=end
12 changes: 12 additions & 0 deletions test/problems/1046.last-stone-weight.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Test

@testset "1046.last-stone-weight.jl" begin

@test last_stone_weight([2, 7, 4, 1, 8, 1]) == 1 # Problem example
@test last_stone_weight([1, 1]) == 0 # All stones cancel out
@test last_stone_weight([5]) == 5 # Single stone
@test last_stone_weight([10, 4, 3]) == 3 # Large differences
@test last_stone_weight([8, 8, 2, 2, 3]) == 1 # Mixed case
@test last_stone_weight([7, 6, 7, 6]) == 0 # Multiple canceling pairs

end
Loading