Skip to content

Commit ec63b96

Browse files
committed
Improved 3457
1 parent 17ed8f2 commit ec63b96

File tree

1 file changed

+32
-18
lines changed

1 file changed

+32
-18
lines changed
Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,40 @@
11
package g3401_3500.s3457_eat_pizzas;
22

3-
// #Medium #Array #Sorting #Greedy #2025_02_18_Time_63_ms_(40.14%)_Space_81.02_MB_(36.94%)
3+
// #Medium #Array #Sorting #Greedy #2025_02_21_Time_16_ms_(100.00%)_Space_75.98_MB_(97.29%)
44

5-
import java.util.Arrays;
6-
7-
public class Solution {
5+
class Solution {
86
public long maxWeight(int[] pizzas) {
9-
int n = pizzas.length;
10-
int m = n / 4;
11-
int z = (m + 1) / 2;
12-
int y = m / 2;
13-
int j = 0;
14-
Arrays.sort(pizzas);
15-
long res = 0;
16-
for (int i = 0; i < z; ++i) {
17-
res += pizzas[n - 1 - j];
18-
j += 1;
7+
int max = 0;
8+
for (int x : pizzas) {
9+
max = Math.max(max, x);
10+
}
11+
int[] count = new int[max + 1];
12+
for (int x : pizzas) {
13+
count[x]++;
14+
}
15+
int m = pizzas.length;
16+
int n = m / 4;
17+
int index = 0;
18+
for (int x = max; x > 0; --x) {
19+
if (count[x] == 0) {
20+
continue;
21+
}
22+
int c = count[x];
23+
while (c-- > 0) {
24+
pizzas[index++] = x;
25+
}
26+
if (index >= m / 2) {
27+
break;
28+
}
29+
}
30+
long ans = 0;
31+
for (int i = 0; i < (n + 1) / 2; ++i) {
32+
ans += pizzas[i];
1933
}
20-
for (int i = 0; i < y; ++i) {
21-
res += pizzas[n - 1 - j - 1];
22-
j += 2;
34+
int k = n - (n + 1) / 2;
35+
for (int i = (n + 1) / 2 + 1; k > 0; i += 2, k--) {
36+
ans += pizzas[i];
2337
}
24-
return res;
38+
return ans;
2539
}
2640
}

0 commit comments

Comments
 (0)