[LeetCode] Collecting Chocolates

2735. Collecting Chocolates

You are given a 0-indexed integer array nums of size n representing the cost of collecting different chocolates. Each chocolate is of a different type, and originally, the chocolate at ith index is of ith type.

In one operation, you can do the following with an incurred cost of x:

  • Simultaneously change the chocolate of ith type to (i + 1)th type for all indexes i where 0 <= i < n - 1. When i == n - 1, that chocolate will be changed to type of the chocolate at index 0.

Return the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
long long minCost(vector<int>& nums, int x) {
long long res = 0, n = nums.size(), sum = 0;
for(int i = 0; i < n; i++) res += nums[i], sum += nums[i];
for(int r = 1; r <= n; r++) {
vector<int> A(n);
for(int i = 0; i < n; i++) {
sum -= nums[i];
A[i] = min(nums[i], nums[(i+1) % n]);
sum += A[i];
}
sum += x;
swap(A,nums);
res = min(res, sum);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/11/PS/LeetCode/collecting-chocolates/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.