LeetCode in Kotlin

3462. Maximum Sum With at Most K Elements

Medium

You are given a 2D integer matrix grid of size n x m, an integer array limits of length n, and an integer k. The task is to find the maximum sum of at most k elements from the matrix grid such that:

Return the maximum sum.

Example 1:

Input: grid = [[1,2],[3,4]], limits = [1,2], k = 2

Output: 7

Explanation:

Example 2:

Input: grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3

Output: 21

Explanation:

Constraints:

Solution

class Solution {
    fun maxSum(grid: Array<IntArray>, limits: IntArray, k: Int): Long {
        var l = 0
        for (i in limits.indices) {
            l += limits[i]
        }
        val dp = IntArray(l)
        var a = 0
        for (i in grid.indices) {
            val lim = limits[i]
            grid[i].sort()
            for (j in grid[i].size - lim..<grid[i].size) {
                dp[a] = grid[i][j]
                a++
            }
        }
        dp.sort()
        var sum = 0L
        for (i in l - 1 downTo l - k) {
            sum += dp[i].toLong()
        }
        return sum
    }
}