Skip to content
Related Articles

Related Articles

Maximize the profit after selling the tickets

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2022

Given array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the tickets. Each seat costs equal to the number of vacant seats in the row it belongs to. The task is to maximize the profit by selling the tickets to N people.

Examples: 

Input: seats[] = {2, 1, 1}, N = 3 
Output:
Person 1: Sell the seat in the row with 
2 vacant seats, seats = {1, 1, 1} 
Person 2: All the rows have 1 vacant 
seat each, seats[] = {0, 1, 1} 
Person 3: seats[] = {0, 0, 1}

Input: seats[] = {2, 3, 4, 5, 1}, N = 6 
Output: 22 
 

Approach: In order to maximize the profit, the ticket must be for the seat in a row which has the maximum number of vacant seats and the number of vacant seats in that row will be decrement by 1 as one of the seats has just been sold. All the persons can be sold a seat ticket until there are vacant seats. This can be computed efficiently with the help of a priority_queue.

Below is the implementation of the above approach: 

C++14




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximized profit
int maxProfit(int seats[], int k, int n)
{
 
    // Push all the vacant seats
    // in a priority queue
    priority_queue<int> pq;
    for (int i = 0; i < k; i++)
        pq.push(seats[i]);
 
    // To store the maximized profit
    int profit = 0;
 
    // To count the people that
    // have been sold a ticket
    int c = 0;
    while (c < n) {
 
        // Get the maximum number of
        // vacant seats for any row
        int top = pq.top();
 
        // Remove it from the queue
        pq.pop();
 
        // If there are no vacant seats
        if (top == 0)
            break;
 
        // Update the profit
        profit = profit + top;
 
        // Push the updated status of the
        // vacant seats in the current row
        pq.push(top - 1);
 
        // Update the count of persons
        c++;
    }
    return profit;
}
 
// Driver code
int main()
{
    int seats[] = { 2, 3, 4, 5, 1 };
    int k = sizeof(seats) / sizeof(int);
    int n = 6;
 
    cout << maxProfit(seats, k, n);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
 
class GFG {
 
// Function to return the maximized profit
static int maxProfit(int seats[], int k, int n)
{
     
    // Push all the vacant seats
    // in a priority queue
    PriorityQueue<Integer> pq;
    pq = new PriorityQueue<>(Collections.reverseOrder());
     
    for(int i = 0; i < k; i++)
       pq.add(seats[i]);
 
    // To store the maximized profit
    int profit = 0;
 
    // To count the people that
    // have been sold a ticket
    int c = 0;
    while (c < n)
    {
 
        // Get the maximum number of
        // vacant seats for any row
        int top = pq.remove();
 
        // If there are no vacant seats
        if (top == 0)
            break;
 
        // Update the profit
        profit = profit + top;
 
        // Push the updated status of the
        // vacant seats in the current row
        pq.add(top - 1);
 
        // Update the count of persons
        c++;
    }
     
    return profit;
}
     
// Driver Code
public static void main(String args[])
{
    int seats[] = { 2, 3, 4, 5, 1 };
    int k = seats.length;
    int n = 6;
 
    System.out.println(maxProfit(seats, k ,n));
}
}
 
// This code is contributed by rutvik_56

Python3




# Python3 implementation of the approach
import heapq
# Function to return the maximized profit
 
 
def maxProfit(seats, k, n):
    # Push all the vacant seats
    # in a max heap
    pq = seats
    # for maintaining the property of max heap
    heapq._heapify_max(pq)
    # To store the maximized profit
    profit = 0
    while n > 0:
        # updating the profit value
        # with maximum number of vacant seats
        profit += pq[0]
        pq[0] -= 1
        # If there are no vacant seats
        if pq[0] == 0:
            break
        # for maintaining the property of max heap
        heapq._heapify_max(pq)
        # decrementing the ticket count
        n -= 1
 
    return profit
 
 
# Driver Code
seats = [2, 3, 4, 5, 1]
k = len(seats)
n = 6
print(maxProfit(seats, k, n))
 
'''Code is written by Rajat Kumar (GLAU)'''

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to return the maximized profit
static int maxProfit(int[] seats, int k, int n)
{
     
    // Push all the vacant seats
    // in a priority queue
    List<int> pq = new List<int>();
    for(int i = 0; i < k; i++)
        pq.Add(seats[i]);
   
    // To store the maximized profit
    int profit = 0;
   
    // To count the people that
    // have been sold a ticket
    int c = 0;
     
    while (c < n)
    {
         
        // Get the maximum number of
        // vacant seats for any row
        pq.Sort();
        pq.Reverse();
        int top = pq[0];
   
        // Remove it from the queue
        pq.RemoveAt(0);
   
        // If there are no vacant seats
        if (top == 0)
            break;
   
        // Update the profit
        profit = profit + top;
   
        // Push the updated status of the
        // vacant seats in the current row
        pq.Add(top - 1);
   
        // Update the count of persons
        c++;
    }
    return profit;
}
 
// Driver Code
static void Main()
{
    int[] seats = { 2, 3, 4, 5, 1 };
    int k = seats.Length;
    int n = 6;
     
    Console.Write(maxProfit(seats, k, n));
}
}
 
// This code is contributed by divyeshrabadiya07

Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the maximized profit
    function maxProfit(seats, k, n)
    {
 
        // Push all the vacant seats
        // in a priority queue
        let priorityQueue = counter.map((item) => item);
 
        // To store the maximized profit
        let profit = 0;
 
        while (n != 0)
        {
 
            // Get the maximum number of
            // vacant seats for any row
            priorityQueue.sort((a,b) => b - a);
            let top = priorityQueue[0];
 
            // Remove it from the queue
            priorityQueue.shift();
 
            // If there are no vacant seats
            if (top == 0)
                break;
 
            // Update the profit
            profit = profit + top;
 
            // Push the updated status of the
            // vacant seats in the current row
            priorityQueue.push(top - 1);
 
            // Update the count of persons
            n--;
        }
        return profit;
    }
     
    let seats = [ 2, 3, 4, 5, 1 ];
    let k = seats.length;
    let n = 6;
      
    document.write(maxProfit(seats, k, n));
 
</script>

Output

22

Time complexity: O(n*log(n))

Auxiliary Space: O(n) 

Sliding Window approach:

The problem can also be solved using the sliding window technique.

  • For each person we need to sell ticket that has the maximum price and decrement its value by 1.
  • Sort the array seats.
  • Maintain two pointers pointing at the current maximum and next maximum number of seats .
  • We iterate till our n>0 and there is a second largest element in the array.
  • In each iteration if seats[i] > seats[j] ,we add the value at seats[i] ,min(n, i-j) times to our answer and decrement the value at ith index else we find j such that seats[j]<seats[i]. If there is no such j we break.
  • If at the end of iteration our n>0 and seats[i]!=0 we add seats[i] till n>0 and seats[i]!=0.

C++




#include <bits/stdc++.h>
using namespace std;
int maxProfit(int seats[],int k, int n)
{
    sort(seats,seats+k);
    int ans = 0;
    int i = k - 1;
    int j = k - 2;
    while (n > 0 && j >= 0) {
        if (seats[i] > seats[j]) {
            ans = ans + min(n, (i - j)) * seats[i];
            n = n - (i - j);
            seats[i]--;
        }
        else {
            while (j >= 0 && seats[j] == seats[i])
                j--;
            if (j < 0)
                break;
            ans = ans + min(n, (i - j)) * seats[i];
            n = n - (i - j);
            seats[i]--;
        }
    }
    while (n > 0 && seats[i] != 0) {
        ans = ans + min(n, k) * seats[i];
        n -= k;
        seats[i]--;
    }
    return ans;
}
int main()
{
    int seats[] = { 2, 3, 4, 5, 1 };
    int k = sizeof(seats) / sizeof(int);
    int n = 6;
 
    cout << maxProfit(seats, k, n);
 
    return 0;
}

Java




// Java program for the above approach
 
import java.util.Arrays;
 
class GFG {
 
    static int maxProfit(int seats[], int k, int n)
    {
        Arrays.sort(seats, 0, k);
        int ans = 0;
        int i = k - 1;
        int j = k - 2;
        while (n > 0 && j >= 0) {
            if (seats[i] > seats[j]) {
                ans = ans + Math.min(n, (i - j)) * seats[i];
                n = n - (i - j);
                seats[i]--;
            }
            else {
 
                while (j >= 0 && seats[j] == seats[i])
                    j--;
 
                if (j < 0)
                    break;
 
                ans = ans + Math.min(n, (i - j)) * seats[i];
                n = n - (i - j);
                seats[i]--;
            }
        }
        while (n > 0 && seats[i] != 0) {
            ans = ans + Math.min(n, k) * seats[i];
            n -= k;
            seats[i]--;
        }
        return ans;
    }
 
    public static void main(String[] args)
    {
        int seats[] = { 2, 3, 4, 5, 1 };
        int k = seats.length;
        int n = 6;
 
        System.out.println(maxProfit(seats, k, n));
    }
}
 
// This code is contributed by rajsanghavi9.

Python3




# Python3 program for the above approach
def maxProfit(seats,k, n):
 
    seats.sort()
     
    ans = 0
    i = k - 1
    j = k - 2
    while (n > 0 and j >= 0):
        if (seats[i] > seats[j]):
            ans = ans + min(n, (i - j)) * seats[i]
            n = n - (i - j)
            seats[i] -= 1
         
        else:
            while (j >= 0 and seats[j] == seats[i]):
                j -= 1
            if (j < 0):
                break
            ans = ans + min(n, (i - j)) * seats[i]
            n = n - (i - j)
            seats[i] -= 1
         
     
    while (n > 0 and seats[i] != 0):
        ans = ans + min(n, k) * seats[i]
        n -= k
        seats[i] -= 1
     
    return ans
 
seats = [2, 3, 4, 5, 1]
k = len(seats)
n = 6
print(maxProfit(seats, k, n))
 
# This code is contributed by shinjanpatra

C#




// C# program for the above approach
 
using System;
 
class GFG {
 
    static int maxProfit(int []seats, int k, int n)
    {
        Array.Sort(seats, 0, k);
        int ans = 0;
        int i = k - 1;
        int j = k - 2;
        while (n > 0 && j >= 0) {
            if (seats[i] > seats[j]) {
                ans = ans + Math.Min(n, (i - j)) * seats[i];
                n = n - (i - j);
                seats[i]--;
            }
            else {
 
                while (j >= 0 && seats[j] == seats[i])
                    j--;
 
                if (j < 0)
                    break;
 
                ans = ans + Math.Min(n, (i - j)) * seats[i];
                n = n - (i - j);
                seats[i]--;
            }
        }
        while (n > 0 && seats[i] != 0) {
            ans = ans + Math.Min(n, k) * seats[i];
            n -= k;
            seats[i]--;
        }
        return ans;
    }
 
    public static void Main(String[] args)
    {
        int []seats = { 2, 3, 4, 5, 1 };
        int k = seats.Length;
        int n = 6;
 
        Console.Write(maxProfit(seats, k, n));
    }
}
 
// This code is contributed by shivanisinghss2110

Javascript




<script>
 
function maxProfit(seats,k, n)
{
    seats.sort();
     
    var ans = 0;
    var i = k - 1;
    var j = k - 2;
    while (n > 0 && j >= 0) {
        if (seats[i] > seats[j]) {
            ans = ans + Math.min(n, (i - j)) * seats[i];
            n = n - (i - j);
            seats[i]--;
        }
        else {
            while (j >= 0 && seats[j] == seats[i])
                j--;
            if (j < 0)
                break;
            ans = ans + Math.min(n, (i - j)) * seats[i];
            n = n - (i - j);
            seats[i]--;
        }
    }
    while (n > 0 && seats[i] != 0) {
        ans = ans + Math.min(n, k) * seats[i];
        n -= k;
        seats[i]--;
    }
    return ans;
}
 
var seats = [2, 3, 4, 5, 1];
var k = seats.length;
var n = 6;
document.write(maxProfit(seats, k, n));
 
// This code is contributed by rrrtnx.
</script>

Output

22

Time Complexity: O(k logk), where k is the size of the given array of seats
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!