Approach 1)
As @nm pointed out a small optimization of the MaxHeap solution:
You do not need to delete tickets one by one. If you have a top window, you need to know how many tickets he has and how many tickets the next one has. Then you can remove the difference and calculate the total price for one operation. With minor changes, you can do the same if you have multiple windows with the same maximum number of tickets.
Approach 2) using a sorted array:
Load the windows into the array. Sort an array. Go back through the array and how you do it: save this number (current), add it to the aggregator, go to the next value. If this is the same (current), then add it to the aggregator, subtract 1 from it, continue driving. If everything is different, go back to the end of the array and start again. Do it N times (inner loop, not outer loop).
Approach 3) using the count array (linear time complexity):
Create an array with index as not. tickets and valuables are gone. from kiosks that have a lot of tickets. So, {0-> 0, 1-> 1, 2-> 0, 3-> 2} means that 1 stall has 1 ticket, and 2 kiosks have 3 tickets)
Start with the highest array index (count -1) and add this index to your aggregator (A), so A = 3, and then decrease this index (3) by 1 to 1 and increase the index below (= 2) by 1 to one.
The array is {0,1,1,1} and A = 3. Repetition. A = 6, the array is {0,1,2,0}. The last index is zero, so move the pointer to index 2.
Repeat so that A = 8, array = {0,2,1,0}. Reiteration. A = 10, the array is {0,5,0,0}.
Stop when you have done this t times (for the number of tickets sold).
Here's the implementation of this approach:
int[] stalls = new int[] { 3,1,3 }; // 2 stalls have 3 tickets each and 1 stall have 1 ticket int t = 4; Arrays.sort(stalls); int tickets = stalls[stalls.length - 1]; int[] dp = new int[tickets + 1]; for (int i = 0; i < stalls.length; i++) { dp[stalls[i]]++; } int total = 0; int i = dp.length - 1; while (t > 0) { if (dp[i] > 0) { total += i; t--; dp[i]--; dp[i - 1]++; } else { i--; } } System.out.println(total);
JerryGoyal
source share