


Monk's favorite game is Football and his favorite club is "Manchester United". Manchester United has qualified for the Champions League Final which is to be held at the Wembley Stadium in London. So, he decided to go there and watch his favorite team play. After reaching the stadium, he saw that many people have lined up for the match tickets. He knows that there are 'M' rows in the stadium with different seating capacities. They may or may not be equal. The price of the ticket depends on the row. If the row has 'K' vacant seats, then the price of the ticket will be 'K' pounds. Now, every football fan standing in the line will get a ticket one by one.
You are given 'N' number of fans waiting for the tickets and seating capacities of different rows. The club wants to gain maximum pounds with the help of ticket sales.
Your task is to print the maximum possible pounds that the club will gain with the help of ticket sales.
The first line of input contains two integers 'M', and 'N', where 'M' denotes the number of rows and 'N' denotes the number of fans waiting in the line to get a ticket.
The second line contains 'M' single space-separated integers where 'VACANT_SEATS[i]' denotes the number of seats initially empty in the ith row.
Output Format:
For each output, print a single integer denoting the maximum pounds the club will earn.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= 'M' <= 5 * 10^5
1 <= 'N' <= 10^9
1 <= 'VACANT_SEATS[i]' <=10^9
Time Limit: 1 sec
4 5
2 3 1 4
14
We have 5 people waiting in line and the possible prices are 2, 3, 1 and 4 (in pounds).
The 1st person is given a ticket in the 4th row worth 4 pounds. Updated possible prices are 2, 3, 1, 3 (in pounds).
The 2nd person is given a ticket in the 4th row worth 3 pounds. Updated possible prices are 2, 3, 1, 2 (in pounds).
The 3rd person is given a ticket in the 2nd row worth 3 pounds. Updated possible prices are 2, 2, 1, 2 (in pounds).
The 4th person is given a ticket in the 2nd row worth 2 pounds. Updated possible prices are 2, 1, 1, 2 (in pounds).
The 5th person is given a ticket in the 1st row worth 2 pounds. Updated possible prices are 1, 1, 1, 2 (in pounds).
Hence, the total money collected is ( 4 + 3 + 3 + 2 + 2 ) = 14 pounds.
6 9
1 5 7 3 9 12
81
One fine approach to the problem can be to sort the array and work on the row with maximum vacant seats and earn the maximum pounds possible until the row with maximum vacant seats changes.
Lets first discuss the approach in steps with an example,
Algorithm:
O(M * logM)) where ‘M’ is the number of seating rows.
We are iterative on an array containing vacant cases also In the worst case, we are sorting the array that contains the number of vacant seats in the ‘M’ number of rows. Hence the overall time complexity will be O(M * logM).
O(1)
We are using constant space here.