LeetCode in Kotlin

3987. Minimum Total Cost to Process All Elements

Medium

You are given an integer array nums and an integer k.

Initially, you have k units of resources.

You must process the elements of nums from left to right. To process the ith element, you need nums[i] resources.

If your available resources are less than nums[i], you may perform an operation that increases your available resources by k. The value of k is fixed and does not change throughout the process. The first such operation incurs a cost of 1, the second incurs a cost of 2, and so on.

After processing the ith element, your available resources decrease by nums[i].

Return an integer denoting the minimum total cost required to process all elements. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: nums = [1,2,3,4], k = 4

Output: 3

Explanation:

Example 2:

Input: nums = [1,1,7,14], k = 4

Output: 15

Explanation:

Example 3:

Input: nums = [1,2,3,4], k = 10

Output: 0

Explanation:

To process all elements, we can use the initial 10 units of resources without performing any operations. Thus, the total cost required is 0.

Constraints:

Solution

class Solution {
    fun minimumCost(nums: IntArray, k: Int): Int {
        var sum = 0L
        val mod = 1000000007
        for (num in nums) {
            sum = sum + num
        }
        if (sum < k) {
            return 0
        }
        val kRequired: Long
        if (sum % k == 0L) {
            kRequired = sum / k
        } else {
            kRequired = sum / k + 1
        }
        return func(kRequired - 1, mod).toInt()
    }

    private fun func(n: Long, mod: Int): Long {
        var ans = ((n % mod) * ((n + 1) % mod)) % mod
        ans = (ans * 500000004) % mod
        return ans
    }
}