Skip to main content
Back to problems
#2735
Medium Algorithms

Collecting chocolates

Array Enumeration
34.7% acceptance
Feb 25, 2026
311
555
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]. Each chocolate is of a different type, and initially, the chocolate at the 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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_cost(nums: Vec<i32>, x: i32) -> i64 {
    let n = nums.len();
    let x = x as i64;
    // min_so_far[i] = min cost for type i with current number of rotations
    let mut min_so_far: Vec<i64> = nums.iter().map(|&v| v as i64).collect();
    let mut best = min_so_far.iter().sum::<i64>(); // k=0
    for k in 1..n {
      for i in 0..n {
        min_so_far[i] = min_so_far[i].min(nums[(i + n - k) % n] as i64);
      }
      let total = k as i64 * x + min_so_far.iter().sum::<i64>();
      best = best.min(total);
    }
    best
  }
}