I found this LeetCode style problem in a previous assignment for my university.
Assume you have an online clothing store and you have products which come in variable sizes. Some products come in the same size multiple times, and you don't want to have any duplicates. Assume the sizes of the products are kept in an array size, of size n. The price of increasing each size[i] by 1 is indicated in the array costs[i]; What is the minimum cost you need to make all sizes unique? For example, if you have the array size = [3,3,4,5] and costs = [5,2,3,1], the minimum cost is 5 in order to modify the array to [3,5,4,6] (modify the second 3 twice and the 5 once: 2*2 + 1 = 5).
I implemented a solution where I have a priority queue where I store all size & cost pairs, ordered by cost descending. The code is similar to the following pseudocode:
var uniqueSizes = new HashSet<int>(); // maintain all unique sizes in a set
int totalCost = 0;
while (pq.Count > 0){
currentPair = pq.Dequeue();
currentSize = currentPair.Item1, currentCost = currentPair.Item2;
while(uniqueSizes.Contains(currentSize){
// keep increasing until I find a size that is not in the set
currentSize++;
totalCost += currentCost;
}
uniqueSizes.Add(currentSize);
}
return totalCost;
My code does run on all tests, but it exceeds time limit on some. I expect that is because I could not find a way to replace the inner while loop, where I keep increasing the currentSize until I find one that is not in the set. I would appreciate any suggestions to make this more time efficient or any alternative solutions which perform in less than O(n^2).
I also expect the code I provided to run in O(n^2) in worst case (outer while: O(n); inner while: worst case, when adding the nth item I need to increase the size n-1 times). Is this assumption correct?
Note: you can solve this in any language you want / even pseudocode, I only care about the algorithm or idea