MediumNo. 2735
Collecting Chocolates — LeetCode 2735 Python Solution
- Topics
- Array, Enumeration
- Reading time
- 2 min
- Source
- leetcode.com
The 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 the index i is nums[i].
Example
- Input
- nums = [20,1,15], x = 5
- Output
- 13
- Explanation
- Initially, the chocolate types are [0,1,2]. We will buy the 1st type of chocolate at a cost of 1.
Python solution
class Solution:
def minCost(self, nums: List[int], x: int) -> int:
n = len(nums)
f = [[0] * n for _ in range(n)]
for i, v in enumerate(nums):
f[i][0] = v
for j in range(1, n):
f[i][j] = min(f[i][j - 1], nums[(i - j) % n])
return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n))Complexity
- Time
- O(n2)
- Space · auxiliary
- O(n2)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1534 | Count Good Triplets | Easy |
| 1566 | Detect Pattern of Length M Repeated K or More Times | Easy |
| 1620 | Coordinate With Maximum Network Quality | Medium |
| 2765 | Longest Alternating Subarray | Easy |
| 2778 | Sum of Squares of Special Elements | Easy |
| 2934 | Minimum Operations to Maximize Last Elements in Arrays | Medium |
Frequently asked questions
- How hard is LeetCode 2735. Collecting Chocolates?
LeetCode 2735. Collecting Chocolates is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2735. Collecting Chocolates?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 2735. Collecting Chocolates?
The Python solution on this page uses O(n2) auxiliary space.
- What topics does LeetCode 2735. Collecting Chocolates cover?
LeetCode 2735. Collecting Chocolates is tagged Array and Enumeration on LeetCode.