Skip to content

Commit 54c903e

Browse files
committed
Added 1046-last-stone-weight.c
1 parent 2b2c9b1 commit 54c903e

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

c/1046-last-stone-weight.c

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int lastStoneWeight(int *stones, int stonesSize) {
5+
while (stonesSize > 1) {
6+
// Find indices of the two largest stones
7+
int max1 = 0, max2 = 1;
8+
if (stones[max2] > stones[max1]) {
9+
int temp = max1;
10+
max1 = max2;
11+
max2 = temp;
12+
}
13+
14+
for (int i = 2; i < stonesSize; i++) {
15+
if (stones[i] > stones[max1]) {
16+
max2 = max1;
17+
max1 = i;
18+
} else if (stones[i] > stones[max2]) {
19+
max2 = i;
20+
}
21+
}
22+
23+
// Smash the stones and update the array
24+
if (stones[max1] != stones[max2]) {
25+
stones[max1] -= stones[max2];
26+
stones[max2] = 0;
27+
} else {
28+
stones[max1] = 0;
29+
stones[max2] = 0;
30+
}
31+
32+
// Remove the smashed stones
33+
int newSize = 0;
34+
for (int i = 0; i < stonesSize; i++) {
35+
if (stones[i] != 0) {
36+
stones[newSize++] = stones[i];
37+
}
38+
}
39+
stonesSize = newSize;
40+
}
41+
42+
return (stonesSize == 0) ? 0 : stones[0];
43+
}
44+
45+
/*
46+
int extractMax(int* stones, int stonesSize) {
47+
int max = stones[0];
48+
for (int i = 1; i < stonesSize; i++) {
49+
if (stones[i] > max) {
50+
max = stones[i];
51+
}
52+
}
53+
for (int i = 0; i < stonesSize; i++) {
54+
if (stones[i] == max) {
55+
stones[i] = 0;
56+
break;
57+
}
58+
}
59+
return max;
60+
}
61+
62+
void insert(int* stones, int stonesSize, int value) {
63+
for (int i = 0; i < stonesSize; i++) {
64+
if (stones[i] == 0) {
65+
stones[i] = value;
66+
return;
67+
}
68+
}
69+
}
70+
71+
int lastStoneWeight(int* stones, int stonesSize) {
72+
while (1) {
73+
int y = extractMax(stones, stonesSize);
74+
int x = extractMax(stones, stonesSize);
75+
if (x == 0) {
76+
return y;
77+
}
78+
if (x != y) {
79+
insert(stones, stonesSize, y - x);
80+
}
81+
}
82+
return 0;
83+
}
84+
*/

0 commit comments

Comments
 (0)