Sponsored
Sponsored
This approach uses a max-heap (priority queue) to efficiently track and retrieve the two heaviest stones. By inserting stones with negative values, we use a min-heap implementation in certain languages to simulate max-heap behavior.
Time Complexity: O(n log n), where n is the number of stones. This accounts for the heap operations.
Space Complexity: O(n), to maintain the heap of stones.
1#include <stdio.h>
2#include <stdlib.h>
3
4int comparator(const void *a, const void *b) {
5 return (*(int *)b) - (*(int *)a);
6}
7
8int lastStoneWeight(int* stones, int stonesSize) {
9 qsort(stones, stonesSize, sizeof(int), comparator);
10 while (stonesSize > 1) {
11 if (stones[0] > stones[1]){
12 stones[1] = stones[0] - stones[1];
13 stones[0] = stones[stonesSize-1];
14 stonesSize--;
15 } else {
16 stones[0] = stones[stonesSize-1];
17 stonesSize -= 2;
18 }
19 qsort(stones, stonesSize, sizeof(int), comparator);
20 }
21 return stonesSize == 1 ? stones[0] : 0;
22}
The C solution uses manual sorting on each loop iteration to handle the 'smashing' operation, effectively simulating what a priority queue would achieve syntactically.
This approach uses a multiset or bag (analogous to balanced trees or sorted lists in some languages) to manage dynamically sorted stone weights. This allows for direct access to largest elements and supports efficient inserts/removals without full re-sorting.
Time Complexity: O(n^2), due to insert and remove operations in SortedList being O(log n).
Space Complexity: O(n), for storage within the SortedList.
1
The C language seeks static sorting per iteration aligning with a balance on sorting overhead faced compared to other similar language solutions here. It leverages manually-driven stone processing continuously re-sorted.