[LeetCode] Minimum Total Cost to Process All Elements

3987. Minimum Total Cost to Process All Elements

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 i^th 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 i^th 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 10^9 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
long long mod = 1e9 + 7;
long long modpow(long long n, long long x, long long mod) {
if(x<0){
return modpow(modpow(n,-x,mod),mod-2,mod);
}
n%=mod;
long long res=1;
while(x){if(x&1){res=res*n%mod;}n=n*n%mod;x>>=1;}return res;
}
public:
long long minimumCost(vector<int>& nums, int k) {
long long op = 0, inv = modpow(2, mod-2, mod), power = k;

for(auto& n : nums) {
if(n <= power) power -= n;
else {
n -= power;
op += n / k;
n %= k;
power = 0;
if(n) {
power = k - n;
op++;
}
}
op %= mod;
}
return op * (op + 1) % mod * inv % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-total-cost-to-process-all-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.