You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2700-2799/2735.Collecting Chocolates/README_EN.md
+80-10
Original file line number
Diff line number
Diff line change
@@ -45,6 +45,30 @@ Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that thi
45
45
46
46
## Solutions
47
47
48
+
**Solution 1: Enumeration**
49
+
50
+
We consider enumerating the number of operations, and define $f[i][j]$ as the minimum cost after performing $j$ operations on the chocolate of type $i$.
51
+
52
+
For the chocolate of type $i$:
53
+
54
+
- If $j = 0$, i.e., no operation is performed, then $f[i][j] = nums[i]$;
55
+
- If $0 \lt j \leq n-1$, then its minimum cost is the minimum cost of the chocolates with indices in the range $[i,.. (i + j) \bmod n]$, i.e., $f[i][j] = \min\{nums[i], nums[i + 1], \cdots, nums[(i + j) \bmod n]\}$, or it can be written as $f[i][j] = \min\{f[i][j - 1], nums[(i + j) \bmod n]\}$.
56
+
- If $j \ge n$, since when $j = n - 1$, the minimum cost of all covered chocolates has been obtained. If $j$ continues to increase, the minimum cost will not change, but the increase in the number of operations will lead to an increase in the final cost. Therefore, we do not need to consider the case where $j \ge n$.
57
+
58
+
In summary, we can get the state transition equation:
Finally, we only need to enumerate the number of operations $j$, calculate the minimum cost under each number of operations, and take the minimum value. That is, the answer is $\min\limits_{0 \leq j \leq n - 1} \sum\limits_{i = 0}^{n - 1} f[i][j] + x \times j$.
69
+
70
+
The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array $nums$.
71
+
48
72
<!-- tabs:start -->
49
73
50
74
### **Python3**
@@ -58,11 +82,7 @@ class Solution:
58
82
f[i][0] = v
59
83
for j inrange(1, n):
60
84
f[i][j] =min(f[i][j -1], nums[(i + j) % n])
61
-
ans = inf
62
-
for j inrange(n):
63
-
cost =sum(f[i][j] for i inrange(n)) + x * j
64
-
ans =min(ans, cost)
65
-
return ans
85
+
returnmin(sum(f[i][j] for i inrange(n)) + x * j for j inrange(n))
0 commit comments