File tree Expand file tree Collapse file tree 1 file changed +16
-22
lines changed
src/main/kotlin/g3401_3500/s3462_maximum_sum_with_at_most_k_elements Expand file tree Collapse file tree 1 file changed +16
-22
lines changed Original file line number Diff line number Diff line change 11package g3401_3500.s3462_maximum_sum_with_at_most_k_elements
22
33// #Medium #Array #Sorting #Greedy #Matrix #Heap_(Priority_Queue)
4- // #2025_02_25_Time_197_ms_(86.21%)_Space_106.34_MB_(6.90%)
5-
6- import java.util.Collections
7- import java.util.PriorityQueue
4+ // #2025_02_25_Time_139_ms_(100.00%)_Space_88.84_MB_(79.31%)
85
96class Solution {
107 fun maxSum (grid : Array <IntArray >, limits : IntArray , k : Int ): Long {
11- if (grid.isEmpty()) {
12- return 0
8+ var l = 0
9+ for (i in limits.indices) {
10+ l + = limits[i]
1311 }
14- val pq = PriorityQueue < Int >( Collections .reverseOrder< Int >() )
15- var temp : PriorityQueue < Int >
12+ val dp = IntArray (l )
13+ var a = 0
1614 for (i in grid.indices) {
17- temp = PriorityQueue <Int >(Collections .reverseOrder<Int >())
18- for (j in grid[i].indices) {
19- temp.add(grid[i][j])
20- }
21- var cnt = 0
22- while (temp.isNotEmpty() && cnt < limits[i]) {
23- pq.add(temp.poll())
24- cnt + = 1
15+ val lim = limits[i]
16+ grid[i].sort()
17+ for (j in grid[i].size - lim.. < grid[i].size) {
18+ dp[a] = grid[i][j]
19+ a++
2520 }
2621 }
27- var result: Long = 0
28- var count: Long = 0
29- while (pq.isNotEmpty() && count < k) {
30- result + = pq.poll()!! .toLong()
31- count + = 1
22+ dp.sort()
23+ var sum = 0L
24+ for (i in l - 1 downTo l - k) {
25+ sum + = dp[i].toLong()
3226 }
33- return result
27+ return sum
3428 }
3529}
You can’t perform that action at this time.
0 commit comments