See why your solution is not working.
Load the stall numbers (second line) into the array. Pass this array N times (the number of tickets to sell), collecting the largest number, adding it to the aggregator, reducing this number. Then you have the total in the aggregator.
This is O (N * M), where N is the number of tickets to sell and M is the number of ticket kiosks. This is largely a brute force approach, which is often not enough to surpass hackerran tests.
Load the stall numbers into an 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 it is the same (current), then add it to the aggregator, subtract 1 from it, continue driving. If it is different, go back to the end of the array and start again. Do it N (inner loop, not outer loop).
Maybe it's me, but I really don't understand what you mean here. From what I see, it looks like it's still O (N * M). How do you handle cases where a large number of tickets has been reduced so many times that it breaks the sorting you did before?
Here you need a data structure that can efficiently retrieve the current maximum and can efficiently add / insert new elements. It seems that the maximum heap is a good candidate. Just save the number of tickets available in each booth in the maximum heap. To sell N tickets with M cabs, do it N times:
- Maximize - O (log (M))
- Add it to the resulting drive - O (1)
- Reduce It - O (1)
- Insert it into the heap - O (log (M))
The overall complexity is O(N*log(M)) , which is probably best.
C ++ implementation:
#include <iostream> #include <vector> #include <algorithm> using namespace std; int max_revenue(vector<int> &tickets, int n) { make_heap(tickets.begin(), tickets.end()); int res = 0; for (int i = 0; i < n; i++) { res += tickets.front(); pop_heap(tickets.begin(), tickets.end()); tickets[tickets.size()-1]--; push_heap(tickets.begin(), tickets.end()); } return res; } int main(void) { int booths; cin >> booths; int n; cin >> n; vector<int> tickets(booths); for (int i = 0; i < booths; i++) cin >> tickets[i]; cout << max_revenue(tickets, n) << endl; return 0; }