C++ Program to find winner and final price in a second price auction event


Suppose we have an array A with n elements. There is a special type of an auction, which is called the second-price auction. In a regular auction, n bidders place a bid which is price a bidder ready to pay. The auction ends, when each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. But here, he pay not the price he offers, but the highest price among the offers of other participants (the second-price auction). A[i] is the price offered by ith bidder. We have to find the winner and the price he will pay. All of the offered prices are unique.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading.

https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

So, if the input of our problem is like A = [3, 8, 2, 9, 4, 14], then the output will be 5, 9, because the winner is at index 5 with prices offered 14, and he will pay 9.

Steps

To solve this, we will follow these steps −

n := size of A
i := index of the maximum element in A
sort the array A
l := A[n - 2]
print i and l

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A){
   int n = A.size();
   int i = max_element(A.begin(), A.end()) - A.begin();
   sort(A.begin(), A.end());
   int l = A[n - 2];
   cout << i << ", " << l;
}
int main(){
   vector<int> A = { 3, 8, 2, 9, 4, 14 };
   solve(A);
}

Input

{ 3, 8, 2, 9, 4, 14 }

Output

5, 9

Updated on: 07-Apr-2022

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements