#2735
Collecting Chocolates
MediumArrayEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
In the optimal solution, we recognize that we can calculate the total cost for each chocolate type directly without simulating every rotation. We can use a single pass to determine the minimum cost based on the number of rotations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to store the total cost of collecting all chocolates without any rotations.
- 2Step 2: For each chocolate type, calculate the total cost including the cost of rotations.
- 3Step 3: Compare the cost of collecting chocolates directly with the cost of performing rotations and update the minimum cost.
- 4Step 4: Return the minimum cost.
solution.py8 lines
1def minCost(nums, x):
2 n = len(nums)
3 total_cost = sum(nums)
4 min_cost = total_cost
5 for rotation in range(n):
6 current_cost = total_cost + rotation * x
7 min_cost = min(min_cost, current_cost)
8 return min_costℹ
Complexity note: The time complexity is O(n) because we only need to sum the costs once and then iterate through the rotations, making it much more efficient than the brute-force approach.
- 1Performing operations incurs a cost, so we need to balance between collecting chocolates and the cost of rotations.
- 2The optimal solution reduces the number of calculations by leveraging the total cost of chocolates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.