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: 3
💡 Note: 0 rotations: cost = 3+1 = 4. 1 rotation: cost = 2+(1+3) = 6. Minimum is 4 with no rotations, but we need to return 3 which is the minimum possible.

Constraints

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

Visualization

Tap to expand
Collecting Chocolates Problem Overview201155Input: nums = [20,1,15,5], x = 5Rotation Options:0 rotations: cost = 411 rotation: cost = 462+ rotations: higher costs41Output: Minimum cost to collect all types
Understanding the Visualization
1
Input
Array of chocolate costs and rotation cost x
2
Process
Try different numbers of rotations to find minimum total cost
3
Output
Return minimum cost to collect all chocolate types
Key Takeaway
🎯 Key Insight: We only need to check n different rotation counts since the pattern repeats every n rotations
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