Maximize the profit after selling the tickets
Last Updated :
12 Jul, 2025
Given array seats[] where seats[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: 4
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>
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.
Python
# 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>
Time Complexity: O(k logk), where k is the size of the given array of seats
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem