Minimize Variation
Learn this problemProblem statement
As an operations engineer at Amazon, you are responsible for organizing the distribution of n different items in the warehouse. The size of each product is provided in an array productSize, where productSize[i] represents the size of the ith product.
You construct a new array called variation, where each element variation[i] is the difference between the largest and smallest product sizes among the first i products. Mathematically, this is defined as:
variation[i] = max(productSize[1], productSize[2], ..., productSize[i]) - min(productSize[1], productSize[2], ..., productSize[i])
Your goal is to arrange the products in a way that minimizes the total variation, i.e., the sum of variation[1] + variation[2] + ... + variation[n]. Determine the minimum possible value of this sum after you have reordered the products.
Function
minimizeVariation(productSize: int[]) → int
Complete the function minimizeVariation in the editor.
My deepest thanks to the incredible friend who helped bring the problem to completion. 🐳
Examples
Example 1
productSize = [3, 1, 2]return = 3productSize = [2,3,1]:
variation[0] = max(2) - min(2) = 2-2 = 0.variation[1] = max(2,3) - min(2,3) = 3-2 = 1.variation[2] = max(2,3,1) - min(2,3,1) = 3-1 = 2.
variation[0] + variation[1] + variation[2] = 0+1+2 = 3. This is the minimum possible total variation after rearranging.Example 2
productSize = [6, 1, 4, 2]return = 9productSize = [1,2,4,6]:
variation[0] = max(1) - min(1) = 1-1 = 0.variation[1] = max(1,2) - min(1,2) = 2-1 = 1.variation[2] = max(1,2,4) - min(1,2,4) = 4-1 = 3.variation[3] = max(1,2,4,6) - min(1,2,4,6) = 6-1 = 5.
variation[0] + variation[1] + variation[2] + variation[3] = 0+1+3+5 = 9.Example 3
productSize = [4, 5, 4, 2, 6, 1, 1]return = 16Example 4
productSize = [6, 1, 4, 2]return = 9Example 5
productSize = [3, 1, 3, 3, 6, 6]return = 11Constraints
1 <= n <= 20001 <= productSize[i] <= 10^9Complete constraints set was added on 06-22-2025 :)More Amazon problems
- Secure Maximum DeliveriesOA · Seen Jul 2026
- Find Median from Data StreamONSITE INTERVIEW · Seen Jul 2026
- Handwritten SigmoidPHONE SCREEN · Seen Jul 2026
- Handwritten SoftmaxPHONE SCREEN · Seen Jul 2026
- Koko Eating BananasONSITE INTERVIEW · Seen Jul 2026
- Loyal Customers Across Two DaysONSITE INTERVIEW · Seen Jul 2026
- Maximum System Memory CapacityOA · Seen Jul 2026
- Package Delivery SystemOA · Seen Jul 2026