LeetCode in Kotlin

2585. Number of Ways to Earn Points

Hard

There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points.

Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 109 + 7.

Note that questions of the same type are indistinguishable.

Example 1:

Input: target = 6, types = [[6,1],[3,2],[2,3]]

Output: 7

Explanation: You can earn 6 points in one of the seven ways:

Example 2:

Input: target = 5, types = [[50,1],[50,2],[50,5]]

Output: 4

Explanation: You can earn 5 points in one of the four ways:

Example 3:

Input: target = 18, types = [[6,1],[3,2],[2,3]]

Output: 1

Explanation: You can only earn 18 points by answering all questions.

Constraints:

Solution

class Solution {
    fun waysToReachTarget(target: Int, types: Array<IntArray>): Int {
        val kMod = 1000000007
        val dp = Array(types.size + 1) { IntArray(target + 1) }
        dp[0][0] = 1
        for (i in 1..types.size) {
            val count = types[i - 1][0]
            val mark = types[i - 1][1]
            for (j in 0..target) for (solved in 0..count) if (j - solved * mark >= 0) {
                dp[i][j] += dp[i - 1][j - solved * mark]
                dp[i][j] %= kMod
            }
        }
        return dp[types.size][target]
    }
}