File tree Expand file tree Collapse file tree 1 file changed +32
-18
lines changed
src/main/java/g3401_3500/s3457_eat_pizzas Expand file tree Collapse file tree 1 file changed +32
-18
lines changed Original file line number Diff line number Diff line change 11package 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}
You can’t perform that action at this time.
0 commit comments