Collecting Chocolates - Problem

You are given a 0-indexed integer array nums of size n representing the cost of collecting different chocolates. The cost of collecting the chocolate at index i is nums[i]. Each chocolate is of a different type, and initially, the chocolate at index i 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) mod n)th type for all chocolates.

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [20,1,15,5], x = 5
Output: 41
💡 Note: Try all rotations: 0 rotations costs 20+1+15+5=41, 1 rotation costs 5+(1+15+5+20)=46, 2 rotations costs 10+(15+5+20+1)=51, 3 rotations costs 15+(5+20+1+15)=56. Minimum is 41.
Example 2 — High Rotation Cost
$ Input: nums = [1,2,3], x = 4
Output: 6
💡 Note: 0 rotations: cost = 1+2+3 = 6. 1 rotation: cost = 4+(2+3+1) = 10. 2 rotations: cost = 8+(3+1+2) = 14. Minimum is 6 with no rotations.
Example 3 — Small Array
$ Input: nums = [3,1], x = 2
Output: 4
💡 Note: 0 rotations: cost = 3+1 = 4. 1 rotation: cost = 2+(1+3) = 6. Minimum is 4 with no rotations.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ x ≤ 106

Visualization

Tap to expand
Collecting Chocolates - Optimized Enumeration INPUT nums array (costs): 20 i=0 1 i=1 15 i=2 5 i=3 Operation cost: x = 5 Type Rotation: T0 T1 T2 T3 ALGORITHM STEPS 1 Track min costs For each type after k ops 2 Enumerate k=0 to n-1 Try all rotation counts 3 Update minimums min[i] = min(costs seen) 4 Calculate total cost sum(mins) + k*x Cost Calculation Table k mins sum+k*x 0 [20,1,15,5] 41+0=41 1 [5,1,1,5] 12+5=17 2 [5,1,1,1] 8+10=18 3 [1,1,1,1] 4+15=19 FINAL RESULT Optimal: k=1 operation After 1 Rotation: 5 20 1 15 Cost Breakdown: Type 0: min(20,5) = 5 Type 1: min(1,20) = 1 Type 2: min(15,1) = 1 Type 3: min(5,15) = 5 Sum: 12 + Op: 5 = 17 Output: 17 Key Insight: After k rotations, each chocolate type i can be collected at minimum cost among positions (i, i-1, i-2, ..., i-k) mod n. We enumerate all k values (0 to n-1) and track running minimums. Total cost = sum of minimum costs for all types + k * operation_cost. Time: O(n^2), Space: O(n) TutorialsPoint - Collecting Chocolates | Optimized Enumeration Approach
Asked in
Google 12 Facebook 8 Amazon 6
8.2K Views
Medium Frequency
~25 min Avg. Time
340 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen