AMAZON Coding Question β Solved
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 i-th 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[0], productSize[1], ..., productSize[i]) - min(productSize[0], productSize[1], ..., productSize[i])
Your goal is to arrange the products in a way that minimizes the total variation, i.e., the sum of variation[0] + variation[1] + ... + variation[n-1]. Determine the minimum possible value of this sum after you have reordered the products.
Example:
n = 3
productSize = [3, 1, 2]
By reordering the products as productSize = [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.
The sum is variation[0] + variation[1] + variation[2] = 0 + 1 + 2 = 3. This is the minimum possible total variation after rearranging.
Function Description:
Complete the function `minimizeVariation` in the editor below.
`minimizeVariation` has the following parameter(s):
- int productSize[n]: The size of each product.
Returns:
- int: The minimum possible total variation after rearranging the array productSize.
Constraints:
- 1 β€ n β€ 2000
- 1 β€ productSize[i] β€ 10^9
Sample Input 0:
productSize = [4, 5, 4, 6, 2, 6, 1, 1]
Sample Output 0:
16
Explanation:
By reordering the products as productSize = [1, 1, 2, 4, 4, 5, 6]:
- variation[0] = max(1) - min(1) = 1 - 1 = 0.
- variation[1] = max(1, 1) - min(1, 1) = 1 - 1 = 0.
- variation[2] = max(1, 1, 2) - min(1, 1, 2) = 2 - 1 = 1.
- variation[3] = max(1, 1, 2, 4) - min(1, 1, 2, 4) = 4 - 1 = 3.
- variation[4] = max(1, 1, 2, 4, 4) - min(1, 1, 2, 4, 4) = 4 - 1 = 3.
- variation[5] = max(1, 1, 2, 4, 4, 5) - min(1, 1, 2, 4, 4, 5) = 5 - 1 = 4.
- variation[6] = max(1, 1, 2, 4, 4, 5, 6) - min(1, 1, 2, 4, 4, 5, 6) = 6 - 1 = 5.
The minimum total variation is variation[0] + variation[1] + variation[2] + variation[3] + variation[4] + variation[5] + variation[6] = 0 + 0 + 1 + 3 + 3 + 4 + 5 = 16.
Asked in:
AMAZON